app.js 469 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233
  1. // Proxmox RouterOS Frontend Application Logic
  2. let state = {
  3. interfaces: [],
  4. vlans: [],
  5. systemStatus: null,
  6. vpnStatus: null,
  7. routes: [],
  8. activeTab: 'dashboard',
  9. fwSubTab: 'filter',
  10. bridgeSubTab: 'bridges',
  11. bridges: [],
  12. bridgePorts: [],
  13. bridgeVLANs: [],
  14. bridgeHosts: [],
  15. bridgeSummary: null,
  16. routesSubTab: 'routes',
  17. pppSubTab: 'secrets',
  18. eoipTunnels: [],
  19. pppSecrets: [],
  20. pppProfiles: [],
  21. pppActiveSessions: [],
  22. pppoeServer: null,
  23. pptpServer: null,
  24. l2tpServer: null,
  25. ipsecServer: null,
  26. ifaceFilter: 'all',
  27. currentModalIface: null,
  28. isPolling: true,
  29. expandedParents: new Set(['eth0']),
  30. pppoeData: null,
  31. wgData: null,
  32. ipsecData: null,
  33. l2tpData: null,
  34. pptpData: null,
  35. fwSummary: null,
  36. filterRules: [],
  37. natRules: [],
  38. mangleRules: [],
  39. addressLists: [],
  40. connections: [],
  41. policyRules: [],
  42. routingTables: [],
  43. routingFilters: [],
  44. filterChainSelected: 'all',
  45. activeToolsSubTab: 'ping',
  46. dhcpClients: [],
  47. dhcpSummary: null
  48. };
  49. const API_BASE = '/api';
  50. function escapeHtml(str) {
  51. if (str === null || str === undefined) return '';
  52. return String(str)
  53. .replace(/&/g, '&')
  54. .replace(/</g, '&lt;')
  55. .replace(/>/g, '&gt;')
  56. .replace(/"/g, '&quot;')
  57. .replace(/'/g, '&#039;');
  58. }
  59. // Initialize on page load
  60. document.addEventListener('DOMContentLoaded', () => {
  61. const hash = window.location.hash.replace('#', '') || 'dashboard';
  62. navigate(hash);
  63. initTableSorting();
  64. fetchData();
  65. // Live polling every 2.5 seconds
  66. setInterval(() => {
  67. if (state.isPolling) {
  68. fetchData(false);
  69. }
  70. }, 2500);
  71. });
  72. // Navigation Handler
  73. function navigate(tabName) {
  74. if (tabName === 'dynamic-routing' || tabName === 'routing') {
  75. navigate('bgp');
  76. return;
  77. }
  78. if (tabName === 'vlans') {
  79. navigate('interfaces');
  80. return;
  81. }
  82. state.activeTab = tabName;
  83. window.location.hash = tabName;
  84. // Update nav links styling
  85. document.querySelectorAll('.nav-link').forEach(link => {
  86. 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';
  87. });
  88. const activeNav = document.getElementById(`nav-${tabName}`);
  89. if (activeNav) {
  90. 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';
  91. }
  92. // Update page headers
  93. const titles = {
  94. dashboard: { title: 'Dashboard Overview', sub: 'Live router performance and network telemetry' },
  95. interfaces: { title: 'Network Interfaces', sub: 'Interface Table View' },
  96. 'dhcp-client': { title: 'DHCP Client', sub: 'DHCP Client List' },
  97. bridge: { title: 'Bridge Interfaces', sub: 'IEEE 802.1D / 802.1Q VLAN-aware Layer 2 switching, RSTP & hardware forwarding (FDB)' },
  98. vlans: { title: 'VLAN Virtual Networks', sub: 'IEEE 802.1Q sub-interface segmentation and routing' },
  99. firewall: { title: 'Network Firewall', sub: 'Stateful packet inspection, NAT, traffic mangle, address lists & connection tracking' },
  100. routes: { title: 'Routing & Policy', sub: 'Routing tables, static routes (DAS/DAC), and policy routing rules' },
  101. bgp: { title: 'BGP Routing (/routing bgp)', sub: 'BIRD 2 BGP Multi-Instance peering sessions, advertised networks, and BGP routing table (RIB)' },
  102. ospf: { title: 'OSPF Routing (/routing ospf)', sub: 'BIRD 2 OSPFv2 link-state routing, dynamic neighbor adjacencies, and multi-area topology' },
  103. 'routing-filters': { title: 'Routing Filters (/routing filter)', sub: 'Route filter chains, prefix matching, BGP community maps & policy-based path control' },
  104. 'dynamic-routing': { title: 'BGP Routing (/routing bgp)', sub: 'BIRD 2 dynamic routing engine' },
  105. ppp: { title: 'PPP Servers & Secrets', sub: 'Subscriber authentication, dynamic IP pools and VPN access concentrators' },
  106. eoip: { title: 'EoIP Tunnels', sub: 'Ethernet over IP (EoIP / GRETAP) Layer 2 encapsulation & transparent network bridging' },
  107. pppoe: { title: 'PPPoE Client WAN', sub: 'Point-to-Point Protocol over Ethernet WAN access' },
  108. wireguard: { title: 'WireGuard VPN', sub: 'High-performance cryptographic Layer 3 tunnels with ChaCha20-Poly1305 key exchange' },
  109. ipsec: { title: 'IPSec (IKEv2) strongSwan', sub: 'Enterprise Site-to-Site & Roadwarrior IPSec controller' },
  110. l2tp: { title: 'L2TP VPN Client', sub: 'Layer 2 Tunneling Protocol via xl2tpd' },
  111. pptp: { title: 'PPTP VPN Client', sub: 'Point-to-Point Tunneling Protocol with MPPE-128 encryption' },
  112. tools: { title: 'Diagnostic & Troubleshooting Tools', sub: 'Network latency analysis, ICMP/MTR telemetry, path tracing, DNS resolution and TCP probing' },
  113. persistence: { title: 'Debian Configuration', sub: 'Native /etc/network/interfaces.d/ persistence manager' }
  114. };
  115. const header = titles[tabName] || titles.dashboard;
  116. const pTitle = document.getElementById('page-title');
  117. if (pTitle) pTitle.innerText = header.title;
  118. const pSub = document.getElementById('page-subtitle');
  119. if (pSub) pSub.innerText = header.sub;
  120. // Toggle sections dynamically for all section elements
  121. document.querySelectorAll('main section[id^="section-"]').forEach(el => {
  122. if (el.id === `section-${tabName}`) {
  123. el.classList.remove('hidden');
  124. } else {
  125. el.classList.add('hidden');
  126. }
  127. });
  128. if (tabName === 'bridge') loadBridge();
  129. if (tabName === 'firewall') loadFirewall();
  130. if (tabName === 'routes') loadRoutes();
  131. if (tabName === 'bgp') {
  132. loadDynamicRouting();
  133. switchBgpSubTab(state.activeBgpSubTab || 'bgp-peers');
  134. }
  135. if (tabName === 'ospf') {
  136. loadDynamicRouting();
  137. switchOspfTab(state.activeOspfTab || 'instances');
  138. }
  139. if (tabName === 'routing-filters') loadDynamicRouting();
  140. if (tabName === 'dynamic-routing') loadDynamicRouting();
  141. if (tabName === 'ppp') loadPPP();
  142. if (tabName === 'eoip') loadEoIP();
  143. if (tabName === 'persistence') loadDebianConfig();
  144. if (tabName === 'pppoe') loadPPPoE();
  145. if (tabName === 'wireguard') loadWireGuard();
  146. if (tabName === 'ipsec') loadIPSec();
  147. if (tabName === 'l2tp') loadL2TP();
  148. if (tabName === 'pptp') loadPPTP();
  149. if (tabName === 'tools') loadToolsView();
  150. if (tabName === 'dhcp-client') loadDHCPClients();
  151. setTimeout(initTableSorting, 50);
  152. }
  153. // Fetch all core system, network and VPN telemetry
  154. async function fetchData(isManual = false) {
  155. const spinner = document.getElementById('refresh-spinner');
  156. if (isManual && spinner) spinner.classList.add('animate-spin');
  157. try {
  158. const [statusRes, ifacesRes, vlansRes, vpnRes, fwRes, dynRes, brSummaryRes, dhcpSumRes, dhcpClientsRes] = await Promise.all([
  159. fetch(`${API_BASE}/system/status`),
  160. fetch(`${API_BASE}/interfaces`),
  161. fetch(`${API_BASE}/vlans`),
  162. fetch(`${API_BASE}/vpn/status`),
  163. fetch(`${API_BASE}/firewall/summary`),
  164. fetch(`${API_BASE}/routing/dynamic/summary`),
  165. fetch(`${API_BASE}/bridge/summary`),
  166. fetch(`${API_BASE}/dhcp/clients/summary`),
  167. fetch(`${API_BASE}/dhcp/clients`)
  168. ]);
  169. if (dhcpSumRes && dhcpSumRes.ok) {
  170. state.dhcpSummary = await dhcpSumRes.json();
  171. const bDhcp = document.getElementById('badge-dhcp-client-count');
  172. if (bDhcp) bDhcp.innerText = state.dhcpSummary?.total_clients || 0;
  173. }
  174. if (dhcpClientsRes && dhcpClientsRes.ok) {
  175. state.dhcpClients = await dhcpClientsRes.json();
  176. }
  177. if (brSummaryRes.ok) {
  178. state.bridgeSummary = await brSummaryRes.json();
  179. const bBridge = document.getElementById('badge-bridge-count');
  180. if (bBridge) bBridge.innerText = state.bridgeSummary?.bridges_count || 0;
  181. const sBr = document.getElementById('bridge-stat-bridges');
  182. if (sBr) sBr.innerText = state.bridgeSummary?.bridges_count || 0;
  183. const sPorts = document.getElementById('bridge-stat-ports');
  184. if (sPorts) sPorts.innerText = state.bridgeSummary?.ports_count || 0;
  185. const sHosts = document.getElementById('bridge-stat-hosts');
  186. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  187. }
  188. if (statusRes.ok) state.systemStatus = await statusRes.json();
  189. if (ifacesRes.ok) {
  190. const ifacesData = await ifacesRes.json();
  191. const rawIfaces = Array.isArray(ifacesData) ? ifacesData : [];
  192. state.interfaces = rawIfaces.filter(i => {
  193. if (!i.name) return false;
  194. if (i.name.startsWith('ep_')) return false;
  195. return !['gre0', 'gretap0', 'erspan0', 'sit0', 'tunl0', 'ip6tnl0', 'ip6gre0', 'ip6erspan0'].includes(i.name);
  196. });
  197. try { populateToolsInterfaces(); } catch (e) {}
  198. }
  199. if (vlansRes.ok) {
  200. const vlansData = await vlansRes.json();
  201. state.vlans = Array.isArray(vlansData) ? vlansData : [];
  202. }
  203. if (vpnRes.ok) state.vpnStatus = await vpnRes.json();
  204. if (fwRes && fwRes.ok) state.fwSummary = await fwRes.json();
  205. if (dynRes && dynRes.ok) state.dynSummary = await dynRes.json();
  206. updateSystemMetrics();
  207. updateBadges();
  208. if (state.activeTab === 'dashboard') renderDashboard();
  209. if (state.activeTab === 'interfaces') renderInterfacesList();
  210. if (state.activeTab === 'vlans') renderVlansList();
  211. if (state.activeTab === 'firewall') loadFirewall(false);
  212. if (state.activeTab === 'routes') loadRoutes(false);
  213. if (state.activeTab === 'dynamic-routing' || state.activeTab === 'bgp' || state.activeTab === 'ospf') loadDynamicRouting(false);
  214. if (state.activeTab === 'ppp') loadPPP(false);
  215. if (state.activeTab === 'eoip') loadEoIP(false);
  216. if (state.activeTab === 'pppoe') loadPPPoE(false);
  217. if (state.activeTab === 'wireguard') loadWireGuard(false);
  218. if (state.activeTab === 'ipsec') loadIPSec(false);
  219. if (state.activeTab === 'l2tp') loadL2TP(false);
  220. if (state.activeTab === 'pptp') loadPPTP(false);
  221. if (state.activeTab === 'dhcp-client') loadDHCPClients(false);
  222. } catch (err) {
  223. console.error('Failed to fetch router state:', err);
  224. } finally {
  225. if (isManual && spinner) {
  226. setTimeout(() => spinner.classList.remove('animate-spin'), 300);
  227. }
  228. }
  229. }
  230. // Update Top KPI and Sidebar Telemetry
  231. function updateSystemMetrics() {
  232. const s = state.systemStatus;
  233. const v = state.vpnStatus;
  234. if (!s) return;
  235. // Sidebar Host & Uptime
  236. const sideHost = document.getElementById('side-hostname');
  237. if (sideHost) sideHost.innerText = s.hostname || 'debian-lxc';
  238. const sideUp = document.getElementById('side-uptime');
  239. if (sideUp) sideUp.innerText = s.uptime_human || '0m';
  240. const sideGw = document.getElementById('side-gateway-ip');
  241. if (sideGw) sideGw.innerText = s.default_gateway ? `GW: ${s.default_gateway}` : 'GW: Isolated';
  242. // Compute CPU Metrics
  243. let cpuPct = 0;
  244. if (s.cpu_pct !== undefined) {
  245. cpuPct = s.cpu_pct;
  246. } else if (s.cpu_load && s.cpu_load.length > 0) {
  247. const cores = s.cpu_cores || 1;
  248. cpuPct = Math.min(100, Math.round((parseFloat(s.cpu_load[0]) / cores) * 100));
  249. }
  250. const cpuPctStr = `${cpuPct.toFixed(1)}%`;
  251. const cpuWidth = `${Math.max(3, Math.min(100, cpuPct))}%`;
  252. const loadStr = s.cpu_load ? s.cpu_load.join(', ') : '-';
  253. // Sidebar CPU
  254. const sideCpuVal = document.getElementById('side-cpu-val');
  255. if (sideCpuVal) sideCpuVal.innerText = cpuPctStr;
  256. const sideCpuBar = document.getElementById('side-cpu-bar');
  257. if (sideCpuBar) {
  258. sideCpuBar.style.width = cpuWidth;
  259. sideCpuBar.title = `Container: ${cpuPctStr} | Host Loadavg: ${loadStr} (${s.cpu_cores || 1} cores)`;
  260. }
  261. // Dashboard CPU Card
  262. const dashCpuVal = document.getElementById('dash-cpu-val');
  263. if (dashCpuVal) dashCpuVal.innerText = cpuPctStr;
  264. const dashCpuBar = document.getElementById('dash-cpu-bar');
  265. if (dashCpuBar) {
  266. dashCpuBar.style.width = cpuWidth;
  267. if (cpuPct > 85) {
  268. dashCpuBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  269. } else if (cpuPct > 65) {
  270. dashCpuBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  271. } else {
  272. dashCpuBar.className = 'h-full rounded-full bg-emerald-500 transition-all duration-500';
  273. }
  274. }
  275. const dashCpuCores = document.getElementById('dash-cpu-cores');
  276. if (dashCpuCores) dashCpuCores.innerText = `${s.cpu_cores || 1} Cores`;
  277. const dashCpuLoad = document.getElementById('dash-cpu-load');
  278. if (dashCpuLoad) dashCpuLoad.innerText = loadStr;
  279. const dashCpuStatus = document.getElementById('dash-cpu-status');
  280. if (dashCpuStatus) {
  281. if (cpuPct > 85) {
  282. dashCpuStatus.innerText = 'High';
  283. dashCpuStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  284. } else if (cpuPct > 65) {
  285. dashCpuStatus.innerText = 'Heavy';
  286. dashCpuStatus.className = 'text-[11px] font-semibold text-amber-400 uppercase px-2 py-0.5 rounded bg-amber-500/10';
  287. } else {
  288. dashCpuStatus.innerText = 'Normal';
  289. dashCpuStatus.className = 'text-[11px] font-semibold text-emerald-400 uppercase px-2 py-0.5 rounded bg-emerald-500/10';
  290. }
  291. }
  292. // Compute RAM Metrics
  293. const memPct = Math.round(s.mem_usage_pct || 0);
  294. const memPctStr = `${memPct}%`;
  295. const memWidth = `${Math.max(3, Math.min(100, memPct))}%`;
  296. const usedMB = s.mem_used_mb || 0;
  297. const totalMB = s.mem_total_mb || 0;
  298. const freeMB = totalMB > usedMB ? totalMB - usedMB : 0;
  299. function fmtMemMB(mb) {
  300. if (mb >= 1024) {
  301. return `${(mb / 1024).toFixed(1)} GB`;
  302. }
  303. return `${mb} MB`;
  304. }
  305. // Sidebar RAM
  306. const sideRamVal = document.getElementById('side-ram-val');
  307. if (sideRamVal) sideRamVal.innerText = memPctStr;
  308. const sideRamBar = document.getElementById('side-ram-bar');
  309. if (sideRamBar) sideRamBar.style.width = memWidth;
  310. // Dashboard RAM Card
  311. const dashRamVal = document.getElementById('dash-ram-val');
  312. if (dashRamVal) dashRamVal.innerText = memPctStr;
  313. const dashRamBar = document.getElementById('dash-ram-bar');
  314. if (dashRamBar) {
  315. dashRamBar.style.width = memWidth;
  316. if (memPct > 85) {
  317. dashRamBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  318. } else if (memPct > 70) {
  319. dashRamBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  320. } else {
  321. dashRamBar.className = 'h-full rounded-full bg-indigo-500 transition-all duration-500';
  322. }
  323. }
  324. const dashRamUsedTotal = document.getElementById('dash-ram-used-total');
  325. if (dashRamUsedTotal) {
  326. dashRamUsedTotal.innerText = `${fmtMemMB(usedMB)} / ${fmtMemMB(totalMB)}`;
  327. }
  328. const dashRamFree = document.getElementById('dash-ram-free');
  329. if (dashRamFree) {
  330. dashRamFree.innerText = fmtMemMB(freeMB);
  331. }
  332. const dashRamStatus = document.getElementById('dash-ram-status');
  333. if (dashRamStatus) {
  334. if (memPct > 85) {
  335. dashRamStatus.innerText = 'High';
  336. dashRamStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  337. } else {
  338. dashRamStatus.innerText = 'Active';
  339. dashRamStatus.className = 'text-[11px] font-semibold text-indigo-400 uppercase px-2 py-0.5 rounded bg-indigo-500/10';
  340. }
  341. }
  342. // Legacy Dashboard Stats (Safe checks)
  343. const elIfacesUp = document.getElementById('stat-ifaces-up');
  344. if (elIfacesUp) elIfacesUp.innerText = s.up_ifaces || 0;
  345. const elIfacesTot = document.getElementById('stat-ifaces-total');
  346. if (elIfacesTot) elIfacesTot.innerText = `${s.total_ifaces || 0} Total`;
  347. const elIfacesDown = document.getElementById('stat-ifaces-down');
  348. if (elIfacesDown) elIfacesDown.innerText = `${s.down_ifaces || 0} DOWN`;
  349. const elVlans = document.getElementById('stat-vlans-count');
  350. if (elVlans) elVlans.innerText = s.vlan_ifaces || 0;
  351. // VPN Status Indicators
  352. if (v) {
  353. const totalActive = v.total_active_tunnels || 0;
  354. const statVpnActive = document.getElementById('stat-vpn-active');
  355. if (statVpnActive) statVpnActive.innerText = totalActive;
  356. const tunnelsDot = document.getElementById('tunnels-dot');
  357. const tunnelsLabel = document.getElementById('tunnels-label');
  358. if (tunnelsDot && tunnelsLabel) {
  359. if (totalActive > 0) {
  360. tunnelsDot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  361. tunnelsLabel.innerText = `${totalActive} Active VPN Tunnel${totalActive > 1 ? 's' : ''}`;
  362. } else {
  363. tunnelsDot.className = 'w-2 h-2 rounded-full bg-slate-500';
  364. tunnelsLabel.innerText = '0 Active VPN Tunnels';
  365. }
  366. }
  367. setDotBadge('badge-pppoe-status', (v.active_pppoe || 0) > 0 || v.pppoe_connected);
  368. setDotBadge('badge-wg-status', (v.active_wireguard || 0) > 0 || v.wireguard_active);
  369. setDotBadge('badge-ipsec-status', (v.active_ipsec || 0) > 0 || v.ipsec_active);
  370. setDotBadge('badge-l2tp-status', (v.active_l2tp || 0) > 0 || v.l2tp_connected);
  371. setDotBadge('badge-pptp-status', (v.active_pptp || 0) > 0 || v.pptp_connected);
  372. }
  373. // Total Live Bandwidth Rate
  374. let totalRx = 0;
  375. let totalTx = 0;
  376. (state.interfaces || []).forEach(i => {
  377. if (i.rate) {
  378. totalRx += i.rate.rx_bytes_sec || 0;
  379. totalTx += i.rate.tx_bytes_sec || 0;
  380. }
  381. });
  382. document.getElementById('stat-traffic-rx').innerText = formatTraffic(totalRx);
  383. document.getElementById('stat-traffic-tx').innerText = formatTraffic(totalTx);
  384. }
  385. function setDotBadge(id, active) {
  386. const el = document.getElementById(id);
  387. if (!el) return;
  388. if (active) {
  389. el.className = 'w-2 h-2 rounded-full bg-emerald-400 shadow-sm shadow-emerald-400/80';
  390. } else {
  391. el.className = 'w-2 h-2 rounded-full bg-slate-600';
  392. }
  393. }
  394. function updateBadges() {
  395. const bIfaces = document.getElementById('badge-ifaces-count');
  396. if (bIfaces) bIfaces.innerText = (state.interfaces || []).length;
  397. const bVlans = document.getElementById('badge-vlans-count');
  398. if (bVlans) bVlans.innerText = (state.vlans || []).length;
  399. if (state.fwSummary) {
  400. const totalFwRules = (state.fwSummary.filter_rules_count || 0) + (state.fwSummary.nat_rules_count || 0) + (state.fwSummary.mangle_rules_count || 0);
  401. const badgeFw = document.getElementById('badge-firewall-count');
  402. if (badgeFw) badgeFw.innerText = totalFwRules;
  403. }
  404. if (state.vpnStatus) {
  405. const v = state.vpnStatus;
  406. const bEoIP = document.getElementById('badge-eoip-count');
  407. if (bEoIP) bEoIP.innerText = v.total_eoip || 0;
  408. const bPPPSess = document.getElementById('badge-ppp-sessions');
  409. if (bPPPSess) bPPPSess.innerText = v.total_ppp_sessions || 0;
  410. setDotBadge('badge-pppoe-status', v.active_pppoe > 0 || v.pppoe_server_running);
  411. setDotBadge('badge-wg-status', v.active_wireguard > 0);
  412. setDotBadge('badge-ipsec-status', v.active_ipsec > 0 || v.ipsec_server_running);
  413. setDotBadge('badge-l2tp-status', v.active_l2tp > 0 || v.l2tp_server_running);
  414. setDotBadge('badge-pptp-status', v.active_pptp > 0 || v.pptp_server_running);
  415. }
  416. if (state.dynSummary) {
  417. const d = state.dynSummary;
  418. setDotBadge('badge-bgp-dot', d.bgp_running);
  419. setDotBadge('badge-ospf-dot', d.ospf_running);
  420. const bBgp = document.getElementById('badge-bgp-count');
  421. if (bBgp) bBgp.innerText = (state.bgpPeers || []).length;
  422. const bOspf = document.getElementById('badge-ospf-count');
  423. if (bOspf) bOspf.innerText = (state.ospfInterfaces || []).length;
  424. const bFilters = document.getElementById('badge-filters-count');
  425. if (bFilters) bFilters.innerText = (state.routingFilters || []).length;
  426. }
  427. }
  428. // Render Dashboard View
  429. function renderDashboard() {
  430. const matrix = document.getElementById('port-matrix');
  431. matrix.innerHTML = '';
  432. (state.interfaces || []).forEach(iface => {
  433. const isUp = iface.state === 'UP';
  434. const isVlan = iface.is_vlan;
  435. const portCard = document.createElement('div');
  436. portCard.className = `p-3 rounded-xl border transition-all cursor-pointer select-none group ${
  437. isUp
  438. ? (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')
  439. : 'bg-slate-900/40 border-slate-800/60 opacity-60 hover:opacity-100 hover:border-slate-700'
  440. }`;
  441. portCard.onclick = () => openIfaceModal(iface.name);
  442. let statusPillClass = isUp ? 'bg-emerald-500 shadow-sm shadow-emerald-500/50' : 'bg-rose-500';
  443. if (isVlan) statusPillClass = isUp ? 'bg-cyan-400 shadow-sm shadow-cyan-400/50' : 'bg-rose-500';
  444. portCard.innerHTML = `
  445. <div class="flex items-center justify-between mb-2">
  446. <span class="font-bold text-xs font-mono text-white group-hover:text-brand-400 transition truncate">${iface.name}</span>
  447. <span class="w-2 h-2 rounded-full ${statusPillClass}"></span>
  448. </div>
  449. <div class="text-[11px] font-mono text-slate-300 truncate">${iface.ipv4 && iface.ipv4.length > 0 ? iface.ipv4[0] : (iface.mac || 'No IP')}</div>
  450. <div class="mt-2 flex items-center justify-between text-[10px] text-slate-400">
  451. <span class="uppercase tracking-wider font-semibold">${isVlan ? `VLAN ${iface.vlan_id}` : iface.type}</span>
  452. <span>${iface.rate?.rx_human || '0 B/s'}</span>
  453. </div>
  454. `;
  455. matrix.appendChild(portCard);
  456. });
  457. const ifaceTbody = document.getElementById('quick-interfaces-table');
  458. if (ifaceTbody) {
  459. ifaceTbody.innerHTML = '';
  460. (state.interfaces || []).forEach(i => {
  461. const isUp = i.state === 'UP';
  462. const tr = document.createElement('tr');
  463. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  464. tr.onclick = () => openIfaceModal(i.name);
  465. const rxStr = i.rate?.rx_human || '0 B/s';
  466. const txStr = i.rate?.tx_human || '0 B/s';
  467. tr.innerHTML = `
  468. <td class="py-2.5 font-bold text-white flex items-center gap-2">
  469. <span class="w-2 h-2 rounded-full ${isUp ? 'bg-emerald-400 shadow-sm shadow-emerald-400/50' : 'bg-rose-400'}"></span>
  470. <span>${i.name}</span>
  471. </td>
  472. <td class="py-2.5 text-slate-300 font-sans">
  473. <span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 font-medium">${i.role || i.type || 'Ethernet'}</span>
  474. </td>
  475. <td class="py-2.5 text-slate-400 text-[11px] font-mono">${i.mac || '-'}</td>
  476. <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>
  477. <td class="py-2.5 text-slate-300 text-[11px] font-mono">
  478. <span class="text-emerald-400">↓ ${rxStr}</span> <span class="text-slate-600">•</span> <span class="text-cyan-400">↑ ${txStr}</span>
  479. </td>
  480. <td class="py-2.5 text-right font-sans font-semibold">
  481. <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>
  482. </td>
  483. `;
  484. ifaceTbody.appendChild(tr);
  485. });
  486. }
  487. const vlanTbody = document.getElementById('quick-vlans-table');
  488. if (vlanTbody) {
  489. vlanTbody.innerHTML = '';
  490. }
  491. }
  492. // Expand / Collapse Handlers
  493. function toggleExpand(parentName) {
  494. if (state.expandedParents.has(parentName)) {
  495. state.expandedParents.delete(parentName);
  496. } else {
  497. state.expandedParents.add(parentName);
  498. }
  499. renderInterfacesList();
  500. }
  501. // VLAN Support Checker: 802.1Q sub-interfaces are only supported on physical ethernet, veth, bridge, bond
  502. function supportsVLAN(iface) {
  503. if (!iface) return false;
  504. if (iface.is_vlan) return false;
  505. const name = (iface.name || '').toLowerCase();
  506. const type = (iface.type || '').toLowerCase();
  507. const role = (iface.role || '').toLowerCase();
  508. // Exclude loopback
  509. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  510. // Exclude WireGuard (Layer 3 tunnel, no 802.1Q support)
  511. if (type === 'wireguard' || name.startsWith('wg')) return false;
  512. // Exclude PPP / PPPoE
  513. if (type === 'ppp' || name.startsWith('ppp')) return false;
  514. // Exclude other Layer 3 tunnels and dummy devices
  515. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  516. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  517. return false;
  518. }
  519. // If name already contains a dot, it's already a sub-interface
  520. if (name.includes('.')) return false;
  521. return true;
  522. }
  523. // Expand / Collapse Handlers
  524. function toggleExpand(parentName) {
  525. const childVlans = (state.vlans || []).filter(v => v.parent_name === parentName || v.name.startsWith(parentName + '.'));
  526. if (childVlans.length === 0) {
  527. // Cannot expand an interface with no VLANs
  528. state.expandedParents.delete(parentName);
  529. return;
  530. }
  531. if (state.expandedParents.has(parentName)) {
  532. state.expandedParents.delete(parentName);
  533. } else {
  534. state.expandedParents.add(parentName);
  535. }
  536. renderInterfacesList();
  537. }
  538. function expandAllIfaces(expand) {
  539. if (expand) {
  540. (state.interfaces || []).forEach(i => {
  541. const hasVlans = (state.vlans || []).some(v => v.parent_name === i.name || v.name.startsWith(i.name + '.'));
  542. if (!i.is_vlan && hasVlans) state.expandedParents.add(i.name);
  543. });
  544. } else {
  545. state.expandedParents.clear();
  546. }
  547. renderInterfacesList();
  548. }
  549. // Filter and Render Hierarchical Interfaces List
  550. function filterIfaces(filter) {
  551. state.ifaceFilter = filter || 'all';
  552. renderInterfacesList();
  553. }
  554. function renderInterfacesList() {
  555. const tbody = document.getElementById('interfaces-tree-tbody');
  556. const emptyState = document.getElementById('interfaces-empty-state');
  557. const summary = document.getElementById('ifaces-list-summary');
  558. const query = (document.getElementById('iface-search')?.value || '').trim().toLowerCase();
  559. tbody.innerHTML = '';
  560. const allIfaces = state.interfaces || [];
  561. const allVlans = state.vlans || [];
  562. const parentIfaces = allIfaces.filter(i => !i.is_vlan);
  563. const filteredParents = parentIfaces.filter(parent => {
  564. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  565. if (query) {
  566. const matchName = parent.name.toLowerCase().includes(query);
  567. const matchIp = (parent.ipv4 || []).some(ip => ip.toLowerCase().includes(query));
  568. const matchRole = (parent.role || '').toLowerCase().includes(query);
  569. const matchType = (parent.type || '').toLowerCase().includes(query);
  570. const matchVlan = childVlans.some(v =>
  571. v.name.toLowerCase().includes(query) ||
  572. String(v.vlan_id).includes(query) ||
  573. (v.ipv4 || []).some(ip => ip.toLowerCase().includes(query)) ||
  574. (v.description || '').toLowerCase().includes(query)
  575. );
  576. if (!matchName && !matchIp && !matchRole && !matchType && !matchVlan) return false;
  577. }
  578. if (state.ifaceFilter === 'has_vlans') return childVlans.length > 0;
  579. if (state.ifaceFilter === 'physical') return parent.type !== 'loopback';
  580. if (state.ifaceFilter === 'up') return parent.state === 'UP';
  581. return true;
  582. });
  583. if (summary) {
  584. summary.innerText = `${parentIfaces.length} Interfaces • ${allVlans.length} Active VLANs`;
  585. }
  586. if (filteredParents.length === 0) {
  587. emptyState?.classList.remove('hidden');
  588. return;
  589. }
  590. emptyState?.classList.add('hidden');
  591. filteredParents.forEach(parent => {
  592. const isUp = parent.state === 'UP';
  593. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  594. const hasVlans = childVlans.length > 0;
  595. const isExpanded = hasVlans && state.expandedParents.has(parent.name);
  596. const canHaveVlan = supportsVLAN(parent);
  597. const parentRow = document.createElement('tr');
  598. parentRow.className = `hover:bg-slate-800/50 transition border-b border-slate-800/80 ${isExpanded ? 'bg-slate-900/80' : ''}`;
  599. parentRow.innerHTML = `
  600. <td class="py-3 px-3 text-center">
  601. ${hasVlans ? `
  602. <button onclick="toggleExpand('${parent.name}')" title="${isExpanded ? 'Collapse VLANs' : 'Expand VLANs'}"
  603. class="w-6 h-6 rounded flex items-center justify-center hover:bg-slate-800 text-slate-400 hover:text-white transition">
  604. <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">
  605. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M9 5l7 7-7 7" />
  606. </svg>
  607. </button>
  608. ` : `
  609. <div class="w-6 h-6 flex items-center justify-center text-slate-700 select-none">
  610. <span class="w-1.5 h-1.5 rounded-full bg-slate-800"></span>
  611. </div>
  612. `}
  613. </td>
  614. <td class="py-3 px-4">
  615. <div class="flex items-center space-x-2.5">
  616. <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">
  617. ${parent.type === 'loopback' ? 'LO' : (parent.type === 'wireguard' ? 'WG' : (parent.type === 'bridge' ? 'BR' : 'NIC'))}
  618. </div>
  619. <div>
  620. <div class="flex items-center gap-2">
  621. ${hasVlans ? `
  622. <span class="font-bold text-white text-sm cursor-pointer hover:text-cyan-400" onclick="toggleExpand('${parent.name}')">${parent.name}</span>
  623. <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>
  624. ` : `
  625. <span class="font-bold text-white text-sm">${parent.name}</span>
  626. <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>
  627. `}
  628. </div>
  629. <div class="text-[10px] text-slate-500 font-sans mt-0.5">${parent.type}</div>
  630. </div>
  631. </div>
  632. </td>
  633. <td class="py-3 px-4 font-sans">
  634. <div class="flex items-center gap-1.5">
  635. <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>
  636. <span class="text-xs text-slate-400 truncate max-w-[120px]">${parent.description || '-'}</span>
  637. </div>
  638. </td>
  639. <td class="py-3 px-4">
  640. ${parent.ipv4 && parent.ipv4.length > 0
  641. ? `<div class="text-white font-medium">${parent.ipv4[0]}</div>`
  642. : '<span class="text-slate-600 font-sans">Unassigned</span>'
  643. }
  644. ${(() => {
  645. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  646. if (!c) return '';
  647. 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');
  648. 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>`;
  649. })()}
  650. </td>
  651. <td class="py-3 px-4 text-slate-400 text-[11px]">
  652. <div>${parent.mac || 'N/A'}</div>
  653. <div class="text-[10px] text-slate-500">MTU ${parent.mtu}</div>
  654. </td>
  655. <td class="py-3 px-4 text-[11px]">
  656. <div class="flex items-center space-x-2">
  657. <span class="text-emerald-400">↓ ${parent.rate?.rx_human || '0 B/s'}</span>
  658. <span class="text-cyan-400">↑ ${parent.rate?.tx_human || '0 B/s'}</span>
  659. </div>
  660. </td>
  661. <td class="py-3 px-4 font-sans">
  662. <button onclick="toggleInterfaceState('${parent.name}', '${isUp ? 'down' : 'up'}')"
  663. class="flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full transition ${
  664. 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'
  665. }" title="Click to toggle link status">
  666. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  667. <span>${parent.state}</span>
  668. </button>
  669. </td>
  670. <td class="py-3 px-4 text-right space-x-2 font-sans">
  671. ${(() => {
  672. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  673. if (c) {
  674. 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>`;
  675. }
  676. 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>`;
  677. })()}
  678. ${canHaveVlan ? `
  679. <button onclick="openVlanModal('${parent.name}')"
  680. 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">
  681. + Add VLAN
  682. </button>
  683. ` : ''}
  684. <button onclick="openIfaceModal('${parent.name}')"
  685. 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">
  686. Configure
  687. </button>
  688. </td>
  689. `;
  690. tbody.appendChild(parentRow);
  691. if (isExpanded) {
  692. const drawerRow = document.createElement('tr');
  693. drawerRow.className = 'bg-slate-950/80 border-b border-slate-800/90';
  694. const drawerCell = document.createElement('td');
  695. drawerCell.colSpan = 8;
  696. drawerCell.className = 'p-0';
  697. drawerCell.innerHTML = `
  698. <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">
  699. <div class="flex items-center justify-between mb-3">
  700. <div class="flex items-center space-x-3">
  701. <span class="font-bold text-xs text-white uppercase tracking-wider flex items-center gap-1.5 font-sans">
  702. <span>VLAN Sub-interfaces on <code class="text-cyan-300 lowercase">${parent.name}</code></span>
  703. </span>
  704. <span class="text-[11px] bg-cyan-950 text-cyan-400 px-2 py-0.5 rounded-full border border-cyan-800/60 font-mono">
  705. ${childVlans.length} Attached
  706. </span>
  707. </div>
  708. <button onclick="openVlanModal('${parent.name}')"
  709. 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">
  710. <span>+ Create VLAN on ${parent.name}</span>
  711. </button>
  712. </div>
  713. ${childVlans.length === 0 ? `
  714. <div class="p-6 text-center border border-dashed border-slate-800 rounded-xl bg-slate-900/40 font-sans">
  715. <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>
  716. <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">
  717. <span>+ Create Your First VLAN on ${parent.name}</span>
  718. </button>
  719. </div>
  720. ` : `
  721. <div class="overflow-x-auto rounded-lg border border-slate-800 bg-slate-900/90 shadow-inner">
  722. <table class="w-full text-left text-xs font-mono">
  723. <thead class="text-slate-400 bg-slate-950/70 border-b border-slate-800 uppercase tracking-wider text-[10px] font-sans">
  724. <tr>
  725. <th class="py-2.5 px-4">VLAN ID</th>
  726. <th class="py-2.5 px-4">Interface Device</th>
  727. <th class="py-2.5 px-4">Subnet Gateway</th>
  728. <th class="py-2.5 px-4">Role / Alias</th>
  729. <th class="py-2.5 px-4">MTU</th>
  730. <th class="py-2.5 px-4">Throughput</th>
  731. <th class="py-2.5 px-4">Status</th>
  732. <th class="py-2.5 px-4 text-right">Actions</th>
  733. </tr>
  734. </thead>
  735. <tbody class="divide-y divide-slate-800/70">
  736. ${childVlans.map(v => {
  737. const isVlanUp = v.state === 'UP';
  738. return `
  739. <tr class="hover:bg-slate-800/40 transition">
  740. <td class="py-2.5 px-4">
  741. <span class="px-2 py-0.5 rounded text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800 shadow-sm">
  742. VLAN ${v.vlan_id}
  743. </span>
  744. </td>
  745. <td class="py-2.5 px-4 font-bold text-white flex items-center gap-1.5">
  746. <span class="text-cyan-500">└─</span>
  747. <span>${v.name}</span>
  748. </td>
  749. <td class="py-2.5 px-4 text-emerald-400 font-medium">
  750. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  751. ${(() => {
  752. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  753. if (!c) return '';
  754. 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';
  755. 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>`;
  756. })()}
  757. </td>
  758. <td class="py-2.5 px-4 font-sans text-slate-300">
  759. <span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 mr-1.5">${v.role || 'VLAN'}</span>
  760. <span class="text-slate-400 text-xs">${v.description || '-'}</span>
  761. </td>
  762. <td class="py-2.5 px-4 text-slate-400">${v.mtu}</td>
  763. <td class="py-2.5 px-4 text-[11px]">
  764. <span class="text-emerald-400">↓ ${v.rate?.rx_human || '0 B/s'}</span>
  765. <span class="text-cyan-400 ml-1.5">↑ ${v.rate?.tx_human || '0 B/s'}</span>
  766. </td>
  767. <td class="py-2.5 px-4 font-sans">
  768. <button onclick="toggleInterfaceState('${v.name}', '${isVlanUp ? 'down' : 'up'}')"
  769. class="flex items-center gap-1 text-[11px] font-semibold px-2 py-0.5 rounded-full ${
  770. 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'
  771. }">
  772. <span class="w-1.5 h-1.5 rounded-full ${isVlanUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  773. <span>${v.state}</span>
  774. </button>
  775. </td>
  776. <td class="py-2.5 px-4 text-right space-x-1.5 font-sans">
  777. ${(() => {
  778. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  779. if (c) {
  780. 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>`;
  781. }
  782. 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>`;
  783. })()}
  784. <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>
  785. <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>
  786. </td>
  787. </tr>
  788. `;
  789. }).join('')}
  790. </tbody>
  791. </table>
  792. </div>
  793. `}
  794. </div>
  795. `;
  796. drawerRow.appendChild(drawerCell);
  797. tbody.appendChild(drawerRow);
  798. }
  799. });
  800. }
  801. // Render VLANs Dedicated View
  802. function renderVlansList() {
  803. const tbody = document.getElementById('vlans-table-body');
  804. if (!tbody) return;
  805. const emptyState = document.getElementById('vlans-empty-state');
  806. const countBadge = document.getElementById('vlans-table-count');
  807. const query = (document.getElementById('vlan-search')?.value || '').toLowerCase();
  808. tbody.innerHTML = '';
  809. const allVlans = state.vlans || [];
  810. if (countBadge) countBadge.innerText = allVlans.length;
  811. const filtered = allVlans.filter(v => {
  812. if (!query) return true;
  813. return v.name.toLowerCase().includes(query) ||
  814. String(v.vlan_id).includes(query) ||
  815. (v.description || '').toLowerCase().includes(query) ||
  816. (v.ipv4 && v.ipv4.some(ip => ip.includes(query)));
  817. });
  818. if (allVlans.length === 0) {
  819. emptyState.classList.remove('hidden');
  820. return;
  821. }
  822. emptyState.classList.add('hidden');
  823. filtered.forEach(v => {
  824. const isUp = v.state === 'UP';
  825. const tr = document.createElement('tr');
  826. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  827. tr.innerHTML = `
  828. <td class="py-3 px-4">
  829. <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">
  830. VLAN ${v.vlan_id}
  831. </span>
  832. </td>
  833. <td class="py-3 px-4 font-bold text-white">${v.name}</td>
  834. <td class="py-3 px-4 text-slate-300">
  835. <span class="bg-slate-800 text-slate-200 px-2 py-0.5 rounded text-[11px]">${v.parent_name || 'eth0'}</span>
  836. </td>
  837. <td class="py-3 px-4 text-emerald-400 font-medium">
  838. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  839. </td>
  840. <td class="py-3 px-4 text-slate-300 font-sans">
  841. <span class="text-slate-400 text-xs">${v.description || v.role || '-'}</span>
  842. </td>
  843. <td class="py-3 px-4 text-slate-400">${v.mtu}</td>
  844. <td class="py-3 px-4 font-sans">
  845. <button onclick="toggleInterfaceState('${v.name}', '${isUp ? 'down' : 'up'}')"
  846. class="flex items-center gap-1.5 text-xs font-semibold px-2 py-0.5 rounded-full ${
  847. 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'
  848. }">
  849. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  850. <span>${v.state}</span>
  851. </button>
  852. </td>
  853. <td class="py-3 px-4 text-right space-x-2 font-sans">
  854. <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>
  855. <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>
  856. </td>
  857. `;
  858. tbody.appendChild(tr);
  859. });
  860. }
  861. // Toggle interface UP / DOWN
  862. async function toggleInterfaceState(name, newState) {
  863. try {
  864. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(name)}/state`, {
  865. method: 'POST',
  866. headers: { 'Content-Type': 'application/json' },
  867. body: JSON.stringify({ state: newState })
  868. });
  869. const data = await res.json();
  870. if (res.ok) {
  871. showToast('Interface Updated', `Interface ${name} is now ${newState.toUpperCase()}`, 'success');
  872. fetchData(false);
  873. } else {
  874. showToast('Error', data.message || 'Failed to toggle interface state', 'error');
  875. }
  876. } catch (err) {
  877. showToast('Error', err.message, 'error');
  878. }
  879. }
  880. // ---------------- MikroTik Flag & Utilities ----------------
  881. function renderMikroTikFlag(running, disabled) {
  882. if (running) {
  883. 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>`;
  884. }
  885. if (disabled) {
  886. 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>`;
  887. }
  888. 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>`;
  889. }
  890. function copyToClipboard(text, label = 'Text') {
  891. navigator.clipboard.writeText(text).then(() => {
  892. showToast('Copied', `${label} copied to clipboard`, 'success');
  893. }).catch(() => {
  894. prompt('Copy value:', text);
  895. });
  896. }
  897. // ======================== PPPoE Multi-Instance ========================
  898. async function loadPPPoE(populateInputs = true) {
  899. try {
  900. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`);
  901. const list = await res.json();
  902. state.pppoeList = Array.isArray(list) ? list : [];
  903. const badge = document.getElementById('pppoe-count-badge');
  904. if (badge) badge.innerText = `${state.pppoeList.length} Interface${state.pppoeList.length !== 1 ? 's' : ''}`;
  905. const tbody = document.getElementById('pppoe-table-body');
  906. const empty = document.getElementById('pppoe-empty');
  907. if (!tbody) return;
  908. tbody.innerHTML = '';
  909. if (state.pppoeList.length === 0) {
  910. if (empty) empty.classList.remove('hidden');
  911. } else {
  912. if (empty) empty.classList.add('hidden');
  913. state.pppoeList.forEach(inst => {
  914. const tr = document.createElement('tr');
  915. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  916. tr.innerHTML = `
  917. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  918. <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
  919. <td class="py-2.5 px-3 text-cyan-400 font-mono">${inst.interface}</td>
  920. <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
  921. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
  922. <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
  923. <td class="py-2.5 px-3 text-center">
  924. <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'}">
  925. ${inst.default_route ? 'Yes' : 'No'}
  926. </span>
  927. </td>
  928. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  929. ${inst.running ? `
  930. <button onclick="disconnectPPPoEInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  931. ` : `
  932. <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>
  933. `}
  934. <button onclick="togglePPPoEState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  935. ${inst.disabled ? 'Enable' : 'Disable'}
  936. </button>
  937. <button onclick="openEditPPPoEModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  938. <button onclick="deletePPPoEInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  939. </td>
  940. `;
  941. tbody.appendChild(tr);
  942. });
  943. }
  944. } catch (err) {
  945. console.error('Failed to load PPPoE:', err);
  946. }
  947. }
  948. function openAddPPPoEModal() {
  949. document.getElementById('pppoe-modal-title').innerText = 'Add PPPoE Client Interface';
  950. document.getElementById('pppoe-modal-edit-orig').value = '';
  951. document.getElementById('pppoe-modal-name').value = `pppoe-out${(state.pppoeList || []).length + 1}`;
  952. document.getElementById('pppoe-modal-name').readOnly = false;
  953. document.getElementById('pppoe-modal-user').value = '';
  954. document.getElementById('pppoe-modal-pass').value = '';
  955. document.getElementById('pppoe-modal-service').value = '';
  956. document.getElementById('pppoe-modal-mtu').value = '1492';
  957. document.getElementById('pppoe-modal-defroute').checked = true;
  958. document.getElementById('pppoe-modal-reconnect').checked = true;
  959. document.getElementById('pppoe-modal-disabled').checked = false;
  960. // Populate interfaces
  961. const sel = document.getElementById('pppoe-modal-iface');
  962. sel.innerHTML = '';
  963. (state.interfaces || []).forEach(i => {
  964. if (i.name === 'lo') return;
  965. const opt = document.createElement('option');
  966. opt.value = i.name;
  967. opt.innerText = `${i.name} (${i.role || i.type})`;
  968. sel.appendChild(opt);
  969. });
  970. document.getElementById('pppoe-modal').classList.remove('hidden');
  971. }
  972. function openEditPPPoEModal(name) {
  973. const inst = (state.pppoeList || []).find(i => i.name === name);
  974. if (!inst) return;
  975. document.getElementById('pppoe-modal-title').innerText = `Edit PPPoE Client: ${name}`;
  976. document.getElementById('pppoe-modal-edit-orig').value = name;
  977. document.getElementById('pppoe-modal-name').value = inst.name;
  978. document.getElementById('pppoe-modal-name').readOnly = true;
  979. document.getElementById('pppoe-modal-user').value = inst.username || '';
  980. document.getElementById('pppoe-modal-pass').value = inst.password || '';
  981. document.getElementById('pppoe-modal-service').value = inst.service_name || '';
  982. document.getElementById('pppoe-modal-mtu').value = inst.mtu || 1492;
  983. document.getElementById('pppoe-modal-defroute').checked = inst.default_route ?? true;
  984. document.getElementById('pppoe-modal-reconnect').checked = inst.auto_reconnect ?? true;
  985. document.getElementById('pppoe-modal-disabled').checked = !!inst.disabled;
  986. const sel = document.getElementById('pppoe-modal-iface');
  987. sel.innerHTML = '';
  988. (state.interfaces || []).forEach(i => {
  989. if (i.name === 'lo') return;
  990. const opt = document.createElement('option');
  991. opt.value = i.name;
  992. opt.innerText = `${i.name} (${i.role || i.type})`;
  993. if (i.name === inst.interface) opt.selected = true;
  994. sel.appendChild(opt);
  995. });
  996. document.getElementById('pppoe-modal').classList.remove('hidden');
  997. }
  998. function closePPPoEModal() {
  999. document.getElementById('pppoe-modal').classList.add('hidden');
  1000. }
  1001. async function submitSavePPPoE(e) {
  1002. e.preventDefault();
  1003. const name = document.getElementById('pppoe-modal-name').value.trim();
  1004. const iface = document.getElementById('pppoe-modal-iface').value;
  1005. const user = document.getElementById('pppoe-modal-user').value.trim();
  1006. const pass = document.getElementById('pppoe-modal-pass').value;
  1007. const service = document.getElementById('pppoe-modal-service').value.trim();
  1008. const mtu = parseInt(document.getElementById('pppoe-modal-mtu').value, 10) || 1492;
  1009. const defRoute = document.getElementById('pppoe-modal-defroute').checked;
  1010. const reconnect = document.getElementById('pppoe-modal-reconnect').checked;
  1011. const disabled = document.getElementById('pppoe-modal-disabled').checked;
  1012. try {
  1013. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`, {
  1014. method: 'POST',
  1015. headers: { 'Content-Type': 'application/json' },
  1016. body: JSON.stringify({
  1017. name,
  1018. interface: iface,
  1019. username: user,
  1020. password: pass,
  1021. service_name: service,
  1022. mtu,
  1023. default_route: defRoute,
  1024. auto_reconnect: reconnect,
  1025. disabled
  1026. })
  1027. });
  1028. if (res.ok) {
  1029. showToast('PPPoE Saved', `Configuration for ${name} saved`, 'success');
  1030. closePPPoEModal();
  1031. loadPPPoE(false);
  1032. fetchData(false);
  1033. } else {
  1034. const err = await res.json();
  1035. showToast('Error', err.message || 'Failed to save PPPoE', 'error');
  1036. }
  1037. } catch (err) {
  1038. showToast('Error', err.message, 'error');
  1039. }
  1040. }
  1041. async function connectPPPoEInstance(name) {
  1042. try {
  1043. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1044. if (res.ok) {
  1045. showToast('Connecting', `Dialing ${name}...`, 'info');
  1046. setTimeout(() => loadPPPoE(false), 2000);
  1047. }
  1048. } catch (err) {
  1049. showToast('Error', err.message, 'error');
  1050. }
  1051. }
  1052. async function disconnectPPPoEInstance(name) {
  1053. try {
  1054. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1055. if (res.ok) {
  1056. showToast('Disconnected', `${name} session terminated`, 'info');
  1057. setTimeout(() => loadPPPoE(false), 1000);
  1058. }
  1059. } catch (err) {
  1060. showToast('Error', err.message, 'error');
  1061. }
  1062. }
  1063. async function togglePPPoEState(name, enable) {
  1064. try {
  1065. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/state`, {
  1066. method: 'POST',
  1067. headers: { 'Content-Type': 'application/json' },
  1068. body: JSON.stringify({ enabled: enable })
  1069. });
  1070. if (res.ok) {
  1071. showToast(enable ? 'Enabled' : 'Disabled', `${name} is now ${enable ? 'enabled' : 'disabled'}`, 'info');
  1072. loadPPPoE(false);
  1073. }
  1074. } catch (err) {
  1075. showToast('Error', err.message, 'error');
  1076. }
  1077. }
  1078. async function deletePPPoEInstance(name) {
  1079. if (!confirm(`Are you sure you want to delete PPPoE client ${name}?`)) return;
  1080. try {
  1081. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1082. if (res.ok) {
  1083. showToast('Deleted', `PPPoE client ${name} removed`, 'success');
  1084. loadPPPoE(false);
  1085. fetchData(false);
  1086. }
  1087. } catch (err) {
  1088. showToast('Error', err.message, 'error');
  1089. }
  1090. }
  1091. // ======================== WireGuard Multi-Interface & Multi-Peer ========================
  1092. state.wgSubTab = 'ifaces';
  1093. function switchWGSubTab(tab) {
  1094. state.wgSubTab = tab;
  1095. const ifacesPanel = document.getElementById('wg-subtab-ifaces');
  1096. const peersPanel = document.getElementById('wg-subtab-peers');
  1097. const ifacesBtn = document.getElementById('wg-subtab-btn-ifaces');
  1098. const peersBtn = document.getElementById('wg-subtab-btn-peers');
  1099. if (tab === 'ifaces') {
  1100. ifacesPanel?.classList.remove('hidden');
  1101. peersPanel?.classList.add('hidden');
  1102. 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';
  1103. 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';
  1104. } else {
  1105. ifacesPanel?.classList.add('hidden');
  1106. peersPanel?.classList.remove('hidden');
  1107. 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';
  1108. 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';
  1109. renderWGPeers();
  1110. }
  1111. }
  1112. async function loadWireGuard(populateInputs = true) {
  1113. try {
  1114. const [ifacesRes, peersRes] = await Promise.all([
  1115. fetch(`${API_BASE}/vpn/wireguard/interfaces`),
  1116. fetch(`${API_BASE}/vpn/wireguard/peers`)
  1117. ]);
  1118. const ifaces = ifacesRes.ok ? await ifacesRes.json() : [];
  1119. const peers = peersRes.ok ? await peersRes.json() : [];
  1120. state.wgInterfaces = Array.isArray(ifaces) ? ifaces : [];
  1121. state.wgPeers = Array.isArray(peers) ? peers : [];
  1122. // Badges
  1123. const ifacesCountBadge = document.getElementById('wg-ifaces-count');
  1124. if (ifacesCountBadge) ifacesCountBadge.innerText = `${state.wgInterfaces.length} Interfaces`;
  1125. const peersCountBadge = document.getElementById('wg-peers-count');
  1126. if (peersCountBadge) peersCountBadge.innerText = `${state.wgPeers.length} Peers`;
  1127. const subTabIfaces = document.getElementById('wg-subtab-badge-ifaces');
  1128. if (subTabIfaces) subTabIfaces.innerText = state.wgInterfaces.length;
  1129. const subTabPeers = document.getElementById('wg-subtab-badge-peers');
  1130. if (subTabPeers) subTabPeers.innerText = state.wgPeers.length;
  1131. // Render Interfaces
  1132. const ifacesTbody = document.getElementById('wg-ifaces-table-body');
  1133. const ifacesEmpty = document.getElementById('wg-ifaces-empty');
  1134. if (ifacesTbody) {
  1135. ifacesTbody.innerHTML = '';
  1136. if (state.wgInterfaces.length === 0) {
  1137. if (ifacesEmpty) ifacesEmpty.classList.remove('hidden');
  1138. } else {
  1139. if (ifacesEmpty) ifacesEmpty.classList.add('hidden');
  1140. state.wgInterfaces.forEach(iface => {
  1141. const peersOnIface = state.wgPeers.filter(p => p.interface === iface.name).length;
  1142. const tr = document.createElement('tr');
  1143. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1144. tr.innerHTML = `
  1145. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(iface.running, iface.disabled)}</td>
  1146. <td class="py-2.5 px-3">
  1147. <div class="flex items-center gap-1.5">
  1148. <span class="font-bold text-white">${escapeHtml(iface.name)}</span>
  1149. ${iface.comment ? `<span class="text-[10px] text-slate-400 font-sans italic">(${escapeHtml(iface.comment)})</span>` : ''}
  1150. </div>
  1151. </td>
  1152. <td class="py-2.5 px-3 text-amber-400 font-mono">${iface.listen_port}</td>
  1153. <td class="py-2.5 px-3 text-emerald-400 font-mono">${iface.address || '<span class="text-slate-600 font-sans">--</span>'}</td>
  1154. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1155. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${iface.public_key}', 'Public Key')" title="Click to copy: ${iface.public_key}">
  1156. ${(iface.public_key || '').substring(0, 10)}... 📋
  1157. </span>
  1158. </td>
  1159. <td class="py-2.5 px-3 text-slate-400 font-mono">${iface.mtu || 1420}</td>
  1160. <td class="py-2.5 px-3 text-center">
  1161. <span class="px-2 py-0.5 rounded text-[10px] font-sans bg-slate-800 text-slate-300">${peersOnIface} peer${peersOnIface !== 1 ? 's' : ''}</span>
  1162. </td>
  1163. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  1164. ${iface.running ? `
  1165. <button onclick="stopWGInterface('${iface.name}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Stop</button>
  1166. ` : `
  1167. <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>
  1168. `}
  1169. <button onclick="toggleWGInterfaceState('${iface.name}', ${iface.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white font-medium">
  1170. ${iface.disabled ? 'Enable' : 'Disable'}
  1171. </button>
  1172. <button onclick="openEditWGInterfaceModal('${iface.name}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1173. <button onclick="deleteWGInterface('${iface.name}')" class="text-xs text-slate-500 hover:text-rose-400 font-medium">Delete</button>
  1174. </td>
  1175. `;
  1176. ifacesTbody.appendChild(tr);
  1177. });
  1178. }
  1179. }
  1180. // Populate filter dropdown in peers tab
  1181. const filterSel = document.getElementById('wg-peers-filter-iface');
  1182. if (filterSel) {
  1183. const currentVal = filterSel.value;
  1184. filterSel.innerHTML = '<option value="">All Interfaces</option>';
  1185. state.wgInterfaces.forEach(i => {
  1186. const opt = document.createElement('option');
  1187. opt.value = i.name;
  1188. opt.innerText = i.name;
  1189. if (i.name === currentVal) opt.selected = true;
  1190. filterSel.appendChild(opt);
  1191. });
  1192. }
  1193. renderWGPeers();
  1194. } catch (err) {
  1195. console.error('Failed to load WireGuard:', err);
  1196. }
  1197. }
  1198. function renderWGPeers() {
  1199. const filterSel = document.getElementById('wg-peers-filter-iface');
  1200. const selectedIface = filterSel ? filterSel.value : '';
  1201. const tbody = document.getElementById('wg-peers-table-body');
  1202. const empty = document.getElementById('wg-peers-empty');
  1203. if (!tbody) return;
  1204. tbody.innerHTML = '';
  1205. const filtered = selectedIface ? state.wgPeers.filter(p => p.interface === selectedIface) : state.wgPeers;
  1206. if (filtered.length === 0) {
  1207. if (empty) empty.classList.remove('hidden');
  1208. } else {
  1209. if (empty) empty.classList.add('hidden');
  1210. filtered.forEach(p => {
  1211. const isOnline = p.latest_handshake && !p.latest_handshake.includes('Never');
  1212. const tr = document.createElement('tr');
  1213. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1214. tr.innerHTML = `
  1215. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isOnline, p.disabled)}</td>
  1216. <td class="py-2.5 px-3 font-mono font-bold text-rose-400">${escapeHtml(p.interface)}</td>
  1217. <td class="py-2.5 px-3 font-bold text-white font-sans">${escapeHtml(p.name || 'Unnamed')}</td>
  1218. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1219. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${p.public_key}', 'Peer Public Key')" title="${p.public_key}">
  1220. ${(p.public_key || '').substring(0, 10)}... 📋
  1221. </span>
  1222. </td>
  1223. <td class="py-2.5 px-3 text-emerald-400 font-mono font-semibold">${(p.allowed_ips || []).join(', ')}</td>
  1224. <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>
  1225. <td class="py-2.5 px-3 text-slate-300 font-sans">${p.latest_handshake || 'Never'}</td>
  1226. <td class="py-2.5 px-3 font-mono text-[11px]">
  1227. <span class="text-emerald-400">↓ ${p.transfer_rx_human || '0 B'}</span>
  1228. <span class="text-cyan-400 ml-1">↑ ${p.transfer_tx_human || '0 B'}</span>
  1229. </td>
  1230. <td class="py-2.5 px-3 text-right font-sans space-x-2 whitespace-nowrap">
  1231. <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">
  1232. ${p.disabled ? 'Enable' : 'Disable'}
  1233. </button>
  1234. <button onclick="openEditWGPeerModal('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1235. <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>
  1236. <button onclick="deleteWGPeer('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Delete</button>
  1237. </td>
  1238. `;
  1239. tbody.appendChild(tr);
  1240. });
  1241. }
  1242. }
  1243. function openAddWGInterfaceModal() {
  1244. document.getElementById('wg-iface-modal-title').innerText = 'Add WireGuard Interface';
  1245. document.getElementById('wg-iface-modal-edit-orig').value = '';
  1246. const nameEl = document.getElementById('wg-iface-modal-name');
  1247. nameEl.value = `wg${(state.wgInterfaces || []).length}`;
  1248. nameEl.readOnly = false;
  1249. document.getElementById('wg-iface-modal-port').value = 51820 + (state.wgInterfaces || []).length;
  1250. document.getElementById('wg-iface-modal-addr').value = `10.${10 + (state.wgInterfaces || []).length}.0.1/24`;
  1251. document.getElementById('wg-iface-modal-mtu').value = '1420';
  1252. document.getElementById('wg-iface-modal-comment').value = '';
  1253. document.getElementById('wg-iface-modal-pubkey').value = '';
  1254. document.getElementById('wg-iface-modal-privkey').value = '';
  1255. document.getElementById('wg-iface-modal-disabled').checked = false;
  1256. generateWGInterfaceKeys();
  1257. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1258. }
  1259. function openEditWGInterfaceModal(name) {
  1260. const iface = (state.wgInterfaces || []).find(i => i.name === name);
  1261. if (!iface) return;
  1262. document.getElementById('wg-iface-modal-title').innerText = `Edit WireGuard Interface: ${name}`;
  1263. document.getElementById('wg-iface-modal-edit-orig').value = name;
  1264. const nameEl = document.getElementById('wg-iface-modal-name');
  1265. nameEl.value = iface.name;
  1266. nameEl.readOnly = false; // ALLOW RENAMING
  1267. document.getElementById('wg-iface-modal-port').value = iface.listen_port || 51820;
  1268. document.getElementById('wg-iface-modal-addr').value = iface.address || '';
  1269. document.getElementById('wg-iface-modal-mtu').value = iface.mtu || 1420;
  1270. document.getElementById('wg-iface-modal-comment').value = iface.comment || '';
  1271. document.getElementById('wg-iface-modal-pubkey').value = iface.public_key || '';
  1272. document.getElementById('wg-iface-modal-privkey').value = iface.private_key || '';
  1273. document.getElementById('wg-iface-modal-disabled').checked = !!iface.disabled;
  1274. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1275. }
  1276. function closeAddWGInterfaceModal() {
  1277. document.getElementById('wg-iface-modal').classList.add('hidden');
  1278. }
  1279. async function generateWGInterfaceKeys() {
  1280. try {
  1281. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1282. const keys = await res.json();
  1283. if (res.ok) {
  1284. document.getElementById('wg-iface-modal-privkey').value = keys.private_key;
  1285. document.getElementById('wg-iface-modal-pubkey').value = keys.public_key;
  1286. }
  1287. } catch (err) {
  1288. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1289. }
  1290. }
  1291. async function onWGInterfacePrivKeyInput() {
  1292. const privKey = document.getElementById('wg-iface-modal-privkey').value.trim();
  1293. if (!privKey) return;
  1294. try {
  1295. const res = await fetch(`${API_BASE}/vpn/wireguard/calc-pubkey`, {
  1296. method: 'POST',
  1297. headers: { 'Content-Type': 'application/json' },
  1298. body: JSON.stringify({ private_key: privKey })
  1299. });
  1300. if (res.ok) {
  1301. const data = await res.json();
  1302. if (data.public_key) {
  1303. document.getElementById('wg-iface-modal-pubkey').value = data.public_key;
  1304. }
  1305. }
  1306. } catch (err) {
  1307. // Ignore while typing
  1308. }
  1309. }
  1310. function toggleWGPrivKeyVisibility() {
  1311. const el = document.getElementById('wg-iface-modal-privkey');
  1312. const btn = document.getElementById('btn-toggle-wg-privkey');
  1313. if (el.type === 'password') {
  1314. el.type = 'text';
  1315. btn.innerText = '🙈 Hide';
  1316. } else {
  1317. el.type = 'password';
  1318. btn.innerText = '👁️ Show';
  1319. }
  1320. }
  1321. function copyWGInterfacePubKey() {
  1322. const pub = document.getElementById('wg-iface-modal-pubkey').value;
  1323. if (pub) copyToClipboard(pub, 'Interface Public Key');
  1324. }
  1325. async function submitSaveWGInterface(e) {
  1326. e.preventDefault();
  1327. const origName = document.getElementById('wg-iface-modal-edit-orig').value.trim();
  1328. const name = document.getElementById('wg-iface-modal-name').value.trim();
  1329. const port = parseInt(document.getElementById('wg-iface-modal-port').value, 10) || 51820;
  1330. const addr = document.getElementById('wg-iface-modal-addr').value.trim();
  1331. const mtu = parseInt(document.getElementById('wg-iface-modal-mtu').value, 10) || 1420;
  1332. const comment = document.getElementById('wg-iface-modal-comment').value.trim();
  1333. const pub = document.getElementById('wg-iface-modal-pubkey').value.trim();
  1334. const priv = document.getElementById('wg-iface-modal-privkey').value.trim();
  1335. const disabled = document.getElementById('wg-iface-modal-disabled').checked;
  1336. try {
  1337. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces`, {
  1338. method: 'POST',
  1339. headers: { 'Content-Type': 'application/json' },
  1340. body: JSON.stringify({
  1341. orig_name: origName,
  1342. name,
  1343. listen_port: port,
  1344. address: addr,
  1345. mtu,
  1346. comment,
  1347. public_key: pub,
  1348. private_key: priv,
  1349. disabled
  1350. })
  1351. });
  1352. const data = await res.json();
  1353. if (res.ok) {
  1354. showToast('WireGuard Saved', `Interface ${name} configured successfully`, 'success');
  1355. closeAddWGInterfaceModal();
  1356. loadWireGuard(false);
  1357. fetchData(false);
  1358. } else {
  1359. showToast('Error', data.error || 'Failed to save interface', 'error');
  1360. }
  1361. } catch (err) {
  1362. showToast('Error', err.message, 'error');
  1363. }
  1364. }
  1365. async function startWGInterface(name) {
  1366. try {
  1367. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1368. if (res.ok) {
  1369. showToast('Interface UP', `Started WireGuard interface ${name}`, 'success');
  1370. loadWireGuard(false);
  1371. fetchData(false);
  1372. }
  1373. } catch (err) {
  1374. showToast('Error', err.message, 'error');
  1375. }
  1376. }
  1377. async function stopWGInterface(name) {
  1378. try {
  1379. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1380. if (res.ok) {
  1381. showToast('Interface DOWN', `Stopped WireGuard interface ${name}`, 'info');
  1382. loadWireGuard(false);
  1383. fetchData(false);
  1384. }
  1385. } catch (err) {
  1386. showToast('Error', err.message, 'error');
  1387. }
  1388. }
  1389. async function toggleWGInterfaceState(name, enable) {
  1390. try {
  1391. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/state`, {
  1392. method: 'POST',
  1393. headers: { 'Content-Type': 'application/json' },
  1394. body: JSON.stringify({ enabled: enable })
  1395. });
  1396. if (res.ok) {
  1397. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1398. loadWireGuard(false);
  1399. fetchData(false);
  1400. }
  1401. } catch (err) {
  1402. showToast('Error', err.message, 'error');
  1403. }
  1404. }
  1405. async function deleteWGInterface(name) {
  1406. if (!confirm(`Are you sure you want to delete WireGuard interface ${name}? All associated peers will also be removed.`)) return;
  1407. try {
  1408. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1409. if (res.ok) {
  1410. showToast('Deleted', `Interface ${name} removed`, 'success');
  1411. loadWireGuard(false);
  1412. fetchData(false);
  1413. }
  1414. } catch (err) {
  1415. showToast('Error', err.message, 'error');
  1416. }
  1417. }
  1418. function populateWGPeerIfaceSelect(selectedIface = '') {
  1419. const sel = document.getElementById('wg-peer-modal-iface');
  1420. if (!sel) return;
  1421. sel.innerHTML = '';
  1422. (state.wgInterfaces || []).forEach(i => {
  1423. const opt = document.createElement('option');
  1424. opt.value = i.name;
  1425. opt.innerText = `${i.name} (${i.address || 'No IP'})`;
  1426. if (i.name === selectedIface) opt.selected = true;
  1427. sel.appendChild(opt);
  1428. });
  1429. }
  1430. function openAddWGPeerModal() {
  1431. if ((state.wgInterfaces || []).length === 0) {
  1432. showToast('No Interfaces', 'Please add a WireGuard interface first before adding peers', 'warning');
  1433. openAddWGInterfaceModal();
  1434. return;
  1435. }
  1436. document.getElementById('wg-peer-modal-title').innerText = 'Add WireGuard Peer';
  1437. document.getElementById('wg-peer-modal-edit-orig-iface').value = '';
  1438. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = '';
  1439. populateWGPeerIfaceSelect();
  1440. document.getElementById('wg-peer-modal-name').value = '';
  1441. document.getElementById('wg-peer-modal-pubkey').value = '';
  1442. document.getElementById('wg-peer-modal-allowedips').value = '10.10.0.2/32';
  1443. document.getElementById('wg-peer-modal-endpoint').value = '';
  1444. document.getElementById('wg-peer-modal-port').value = '';
  1445. document.getElementById('wg-peer-modal-keepalive').value = '25';
  1446. document.getElementById('wg-peer-modal-preshared').value = '';
  1447. document.getElementById('wg-peer-modal-disabled').checked = false;
  1448. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  1449. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  1450. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1451. }
  1452. function openEditWGPeerModal(ifaceName, pubKey) {
  1453. const peer = (state.wgPeers || []).find(p => p.interface === ifaceName && p.public_key === pubKey);
  1454. if (!peer) {
  1455. showToast('Not Found', 'Peer not found', 'warning');
  1456. return;
  1457. }
  1458. document.getElementById('wg-peer-modal-title').innerText = `Edit WireGuard Peer (${peer.name || ifaceName})`;
  1459. document.getElementById('wg-peer-modal-edit-orig-iface').value = peer.interface;
  1460. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = peer.public_key;
  1461. populateWGPeerIfaceSelect(peer.interface);
  1462. document.getElementById('wg-peer-modal-name').value = peer.name || '';
  1463. document.getElementById('wg-peer-modal-pubkey').value = peer.public_key || '';
  1464. document.getElementById('wg-peer-modal-allowedips').value = (peer.allowed_ips || []).join(', ');
  1465. document.getElementById('wg-peer-modal-endpoint').value = peer.endpoint_address || '';
  1466. document.getElementById('wg-peer-modal-port').value = peer.endpoint_port || '';
  1467. document.getElementById('wg-peer-modal-keepalive').value = peer.persistent_keepalive ?? 25;
  1468. document.getElementById('wg-peer-modal-preshared').value = peer.preshared_key || '';
  1469. document.getElementById('wg-peer-modal-disabled').checked = !!peer.disabled;
  1470. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  1471. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  1472. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1473. }
  1474. function closeAddWGPeerModal() {
  1475. document.getElementById('wg-peer-modal').classList.add('hidden');
  1476. }
  1477. async function generatePeerKeypairHelper() {
  1478. try {
  1479. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1480. const keys = await res.json();
  1481. if (res.ok) {
  1482. document.getElementById('wg-peer-modal-pubkey').value = keys.public_key;
  1483. document.getElementById('wg-peer-gen-privkey').value = keys.private_key;
  1484. document.getElementById('wg-peer-gen-key-box').classList.remove('hidden');
  1485. checkWGPeerKeyValidity();
  1486. showToast('Keypair Generated', 'Public key inserted and client private key ready to copy', 'info');
  1487. }
  1488. } catch (err) {
  1489. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1490. }
  1491. }
  1492. function copyGeneratedPeerPrivKey() {
  1493. const priv = document.getElementById('wg-peer-gen-privkey').value;
  1494. if (priv) copyToClipboard(priv, 'Client Private Key');
  1495. }
  1496. async function generatePeerPSK() {
  1497. try {
  1498. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1499. const keys = await res.json();
  1500. if (res.ok && keys.private_key) {
  1501. document.getElementById('wg-peer-modal-preshared').value = keys.private_key;
  1502. showToast('PSK Generated', 'Generated 256-bit preshared key', 'info');
  1503. }
  1504. } catch (err) {
  1505. showToast('Error', err.message, 'error');
  1506. }
  1507. }
  1508. function checkWGPeerKeyValidity() {
  1509. const ifaceName = document.getElementById('wg-peer-modal-iface').value;
  1510. const peerPubKey = document.getElementById('wg-peer-modal-pubkey').value.trim();
  1511. const warningEl = document.getElementById('wg-peer-key-warning');
  1512. if (!warningEl) return;
  1513. const targetIface = (state.wgInterfaces || []).find(i => i.name === ifaceName);
  1514. if (targetIface && targetIface.public_key && peerPubKey && targetIface.public_key === peerPubKey) {
  1515. warningEl.classList.remove('hidden');
  1516. } else {
  1517. warningEl.classList.add('hidden');
  1518. }
  1519. }
  1520. async function submitSaveWGPeer(e) {
  1521. e.preventDefault();
  1522. const origIface = document.getElementById('wg-peer-modal-edit-orig-iface').value.trim();
  1523. const origPubKey = document.getElementById('wg-peer-modal-edit-orig-pubkey').value.trim();
  1524. const iface = document.getElementById('wg-peer-modal-iface').value;
  1525. const name = document.getElementById('wg-peer-modal-name').value.trim();
  1526. const pub = document.getElementById('wg-peer-modal-pubkey').value.trim();
  1527. const allowed = document.getElementById('wg-peer-modal-allowedips').value
  1528. .split(',')
  1529. .map(s => s.trim())
  1530. .filter(s => s.length > 0);
  1531. const epHost = document.getElementById('wg-peer-modal-endpoint').value.trim();
  1532. const epPort = parseInt(document.getElementById('wg-peer-modal-port').value, 10) || 0;
  1533. const keepalive = parseInt(document.getElementById('wg-peer-modal-keepalive').value, 10) || 0;
  1534. const psk = document.getElementById('wg-peer-modal-preshared').value.trim();
  1535. const disabled = document.getElementById('wg-peer-modal-disabled').checked;
  1536. // Validation
  1537. const targetIface = (state.wgInterfaces || []).find(i => i.name === iface);
  1538. if (targetIface && targetIface.public_key === pub) {
  1539. showToast('Invalid Peer Key', 'Peer public key cannot be the same as the interface public key!', 'error');
  1540. return;
  1541. }
  1542. try {
  1543. const res = await fetch(`${API_BASE}/vpn/wireguard/peers`, {
  1544. method: 'POST',
  1545. headers: { 'Content-Type': 'application/json' },
  1546. body: JSON.stringify({
  1547. orig_interface: origIface,
  1548. orig_public_key: origPubKey,
  1549. interface: iface,
  1550. name,
  1551. public_key: pub,
  1552. allowed_ips: allowed,
  1553. endpoint_address: epHost,
  1554. endpoint_port: epPort,
  1555. persistent_keepalive: keepalive,
  1556. preshared_key: psk,
  1557. disabled
  1558. })
  1559. });
  1560. const data = await res.json();
  1561. if (res.ok) {
  1562. showToast('Peer Saved', `Peer ${name} saved on ${iface}`, 'success');
  1563. closeAddWGPeerModal();
  1564. loadWireGuard(false);
  1565. } else {
  1566. showToast('Error', data.error || 'Failed to save peer', 'error');
  1567. }
  1568. } catch (err) {
  1569. showToast('Error', err.message, 'error');
  1570. }
  1571. }
  1572. async function toggleWGPeerState(iface, pubkey, enable) {
  1573. try {
  1574. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/state`, {
  1575. method: 'POST',
  1576. headers: { 'Content-Type': 'application/json' },
  1577. body: JSON.stringify({ interface: iface, public_key: pubkey, enabled: enable })
  1578. });
  1579. const data = await res.json();
  1580. if (res.ok) {
  1581. showToast(enable ? 'Peer Enabled' : 'Peer Disabled', `Peer state updated on ${iface}`, 'info');
  1582. loadWireGuard(false);
  1583. } else {
  1584. showToast('Error', data.error || 'Failed to update peer state', 'error');
  1585. }
  1586. } catch (err) {
  1587. showToast('Error', err.message, 'error');
  1588. }
  1589. }
  1590. async function deleteWGPeer(iface, pubkey) {
  1591. if (!confirm(`Are you sure you want to remove peer from ${iface}?`)) return;
  1592. try {
  1593. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/delete`, {
  1594. method: 'POST',
  1595. headers: { 'Content-Type': 'application/json' },
  1596. body: JSON.stringify({ interface: iface, public_key: pubkey })
  1597. });
  1598. const data = await res.json();
  1599. if (res.ok) {
  1600. showToast('Peer Deleted', 'WireGuard peer removed', 'success');
  1601. loadWireGuard(false);
  1602. } else {
  1603. showToast('Error', data.error || 'Failed to remove peer', 'error');
  1604. }
  1605. } catch (err) {
  1606. showToast('Error', err.message, 'error');
  1607. }
  1608. }
  1609. // ======================== IPSec Multi-Tunnel ========================
  1610. async function loadIPSec(populateInputs = true) {
  1611. try {
  1612. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`);
  1613. const list = await res.json();
  1614. state.ipsecTunnels = Array.isArray(list) ? list : [];
  1615. const activeCount = state.ipsecTunnels.filter(t => t.running || t.status === 'ESTABLISHED').length;
  1616. const badge = document.getElementById('ipsec-sas-badge');
  1617. if (badge) badge.innerText = `${activeCount} Active SAs`;
  1618. const tbody = document.getElementById('ipsec-table-body');
  1619. const empty = document.getElementById('ipsec-empty');
  1620. if (!tbody) return;
  1621. tbody.innerHTML = '';
  1622. if (state.ipsecTunnels.length === 0) {
  1623. if (empty) empty.classList.remove('hidden');
  1624. } else {
  1625. if (empty) empty.classList.add('hidden');
  1626. state.ipsecTunnels.forEach(c => {
  1627. const isEstablished = c.running || c.status === 'ESTABLISHED';
  1628. const tr = document.createElement('tr');
  1629. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1630. tr.innerHTML = `
  1631. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isEstablished, c.disabled)}</td>
  1632. <td class="py-2.5 px-4 font-bold text-white">${c.name}</td>
  1633. <td class="py-2.5 px-4 text-emerald-400 font-mono">${c.local_subnet || '-'}</td>
  1634. <td class="py-2.5 px-4 text-slate-300 font-mono">${c.remote_addrs || '-'}</td>
  1635. <td class="py-2.5 px-4 text-cyan-400 font-mono">${c.remote_subnet || '-'}</td>
  1636. <td class="py-2.5 px-4 font-sans">
  1637. <span class="px-2 py-0.5 rounded-full text-[10px] font-semibold ${
  1638. isEstablished ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30' : 'bg-slate-800 text-slate-400'
  1639. }">${c.status || (isEstablished ? 'ESTABLISHED' : 'DISCONNECTED')}</span>
  1640. </td>
  1641. <td class="py-2.5 px-4 text-right space-x-2 font-sans">
  1642. ${isEstablished ? `
  1643. <button onclick="stopIPSecTunnel('${c.name}')" class="text-xs text-rose-400 hover:text-rose-300">Terminate</button>
  1644. ` : `
  1645. <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>
  1646. `}
  1647. <button onclick="toggleIPSecState('${c.name}', ${c.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1648. ${c.disabled ? 'Enable' : 'Disable'}
  1649. </button>
  1650. <button onclick="openEditIPSecModal('${c.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1651. <button onclick="deleteIPSecConn('${c.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1652. </td>
  1653. `;
  1654. tbody.appendChild(tr);
  1655. });
  1656. }
  1657. } catch (err) {
  1658. console.error('Failed to load IPSec:', err);
  1659. }
  1660. }
  1661. function openAddIPSecModal() {
  1662. document.getElementById('ipsec-modal-title').innerText = 'Configure IPSec IKEv2 Tunnel';
  1663. document.getElementById('ipsec-modal-name').value = `ipsec-${(state.ipsecTunnels || []).length + 1}`;
  1664. document.getElementById('ipsec-modal-name').readOnly = false;
  1665. document.getElementById('ipsec-modal-localts').value = '192.168.10.0/24';
  1666. document.getElementById('ipsec-modal-remotets').value = '192.168.20.0/24';
  1667. document.getElementById('ipsec-modal-remotegw').value = '';
  1668. document.getElementById('ipsec-modal-psk').value = '';
  1669. document.getElementById('ipsec-modal-ikeprop').value = 'aes256-sha256-modp2048,default';
  1670. document.getElementById('ipsec-modal-espprop').value = 'aes256-sha256-modp2048,default';
  1671. document.getElementById('ipsec-modal-autostart').checked = true;
  1672. document.getElementById('ipsec-modal-disabled').checked = false;
  1673. document.getElementById('ipsec-modal').classList.remove('hidden');
  1674. }
  1675. function openEditIPSecModal(name) {
  1676. const conn = (state.ipsecTunnels || []).find(c => c.name === name);
  1677. if (!conn) return;
  1678. document.getElementById('ipsec-modal-title').innerText = `Edit IPSec Tunnel: ${name}`;
  1679. document.getElementById('ipsec-modal-name').value = conn.name;
  1680. document.getElementById('ipsec-modal-name').readOnly = true;
  1681. document.getElementById('ipsec-modal-localts').value = conn.local_subnet || '';
  1682. document.getElementById('ipsec-modal-remotets').value = conn.remote_subnet || '';
  1683. document.getElementById('ipsec-modal-remotegw').value = conn.remote_addrs || '';
  1684. document.getElementById('ipsec-modal-psk').value = conn.preshared_key || '';
  1685. document.getElementById('ipsec-modal-ikeprop').value = conn.ike_proposals || 'aes256-sha256-modp2048,default';
  1686. document.getElementById('ipsec-modal-espprop').value = conn.esp_proposals || 'aes256-sha256-modp2048,default';
  1687. document.getElementById('ipsec-modal-autostart').checked = conn.auto_start ?? true;
  1688. document.getElementById('ipsec-modal-disabled').checked = !!conn.disabled;
  1689. document.getElementById('ipsec-modal').classList.remove('hidden');
  1690. }
  1691. function closeAddIPSecModal() {
  1692. document.getElementById('ipsec-modal').classList.add('hidden');
  1693. }
  1694. async function submitSaveIPSec(e) {
  1695. e.preventDefault();
  1696. const name = document.getElementById('ipsec-modal-name').value.trim();
  1697. const localts = document.getElementById('ipsec-modal-localts').value.trim();
  1698. const remotets = document.getElementById('ipsec-modal-remotets').value.trim();
  1699. const remotegw = document.getElementById('ipsec-modal-remotegw').value.trim();
  1700. const psk = document.getElementById('ipsec-modal-psk').value;
  1701. const ike = document.getElementById('ipsec-modal-ikeprop').value.trim();
  1702. const esp = document.getElementById('ipsec-modal-espprop').value.trim();
  1703. const autostart = document.getElementById('ipsec-modal-autostart').checked;
  1704. const disabled = document.getElementById('ipsec-modal-disabled').checked;
  1705. try {
  1706. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`, {
  1707. method: 'POST',
  1708. headers: { 'Content-Type': 'application/json' },
  1709. body: JSON.stringify({
  1710. name,
  1711. local_addrs: '%any',
  1712. remote_addrs: remotegw,
  1713. local_subnet: localts,
  1714. remote_subnet: remotets,
  1715. preshared_key: psk,
  1716. ike_proposals: ike,
  1717. esp_proposals: esp,
  1718. auto_start: autostart,
  1719. disabled
  1720. })
  1721. });
  1722. if (res.ok) {
  1723. showToast('IPSec Saved', `Tunnel ${name} configured`, 'success');
  1724. closeAddIPSecModal();
  1725. loadIPSec(false);
  1726. fetchData(false);
  1727. }
  1728. } catch (err) {
  1729. showToast('Error', err.message, 'error');
  1730. }
  1731. }
  1732. async function startIPSecTunnel(name) {
  1733. try {
  1734. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1735. if (res.ok) {
  1736. showToast('Initiating Tunnel', `Attempting SA handshake for ${name}...`, 'info');
  1737. setTimeout(() => loadIPSec(false), 2000);
  1738. }
  1739. } catch (err) {
  1740. showToast('Error', err.message, 'error');
  1741. }
  1742. }
  1743. async function stopIPSecTunnel(name) {
  1744. try {
  1745. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1746. if (res.ok) {
  1747. showToast('Terminated', `IPSec SA for ${name} closed`, 'info');
  1748. loadIPSec(false);
  1749. }
  1750. } catch (err) {
  1751. showToast('Error', err.message, 'error');
  1752. }
  1753. }
  1754. async function toggleIPSecState(name, enable) {
  1755. try {
  1756. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/state`, {
  1757. method: 'POST',
  1758. headers: { 'Content-Type': 'application/json' },
  1759. body: JSON.stringify({ enabled: enable })
  1760. });
  1761. if (res.ok) {
  1762. showToast(enable ? 'Enabled' : 'Disabled', `IPSec tunnel ${name} updated`, 'info');
  1763. loadIPSec(false);
  1764. }
  1765. } catch (err) {
  1766. showToast('Error', err.message, 'error');
  1767. }
  1768. }
  1769. async function deleteIPSecConn(name) {
  1770. if (!confirm(`Are you sure you want to delete IPSec tunnel ${name}?`)) return;
  1771. try {
  1772. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1773. if (res.ok) {
  1774. showToast('Deleted', `IPSec connection ${name} removed`, 'success');
  1775. loadIPSec(false);
  1776. fetchData(false);
  1777. }
  1778. } catch (err) {
  1779. showToast('Error', err.message, 'error');
  1780. }
  1781. }
  1782. // ======================== L2TP Multi-Instance ========================
  1783. async function loadL2TP(populateInputs = true) {
  1784. try {
  1785. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`);
  1786. const list = await res.json();
  1787. state.l2tpList = Array.isArray(list) ? list : [];
  1788. const badge = document.getElementById('l2tp-count-badge');
  1789. if (badge) badge.innerText = `${state.l2tpList.length} Client${state.l2tpList.length !== 1 ? 's' : ''}`;
  1790. const tbody = document.getElementById('l2tp-table-body');
  1791. const empty = document.getElementById('l2tp-empty');
  1792. if (!tbody) return;
  1793. tbody.innerHTML = '';
  1794. if (state.l2tpList.length === 0) {
  1795. if (empty) empty.classList.remove('hidden');
  1796. } else {
  1797. if (empty) empty.classList.add('hidden');
  1798. state.l2tpList.forEach(inst => {
  1799. const tr = document.createElement('tr');
  1800. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1801. tr.innerHTML = `
  1802. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1803. <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
  1804. <td class="py-2.5 px-3 text-cyan-400 font-mono">${inst.connect_to}</td>
  1805. <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
  1806. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
  1807. <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
  1808. <td class="py-2.5 px-3 text-center">
  1809. <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'}">
  1810. ${inst.default_route ? 'Yes' : 'No'}
  1811. </span>
  1812. </td>
  1813. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1814. ${inst.running ? `
  1815. <button onclick="disconnectL2TPInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1816. ` : `
  1817. <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>
  1818. `}
  1819. <button onclick="toggleL2TPState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1820. ${inst.disabled ? 'Enable' : 'Disable'}
  1821. </button>
  1822. <button onclick="openEditL2TPModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1823. <button onclick="deleteL2TPInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1824. </td>
  1825. `;
  1826. tbody.appendChild(tr);
  1827. });
  1828. }
  1829. } catch (err) {
  1830. console.error('Failed to load L2TP:', err);
  1831. }
  1832. }
  1833. function openAddL2TPModal() {
  1834. document.getElementById('l2tp-modal-title').innerText = 'Add L2TP Client Interface';
  1835. document.getElementById('l2tp-modal-name').value = `l2tp-out${(state.l2tpList || []).length + 1}`;
  1836. document.getElementById('l2tp-modal-name').readOnly = false;
  1837. document.getElementById('l2tp-modal-server').value = '';
  1838. document.getElementById('l2tp-modal-user').value = '';
  1839. document.getElementById('l2tp-modal-pass').value = '';
  1840. document.getElementById('l2tp-modal-ipsec').value = '';
  1841. document.getElementById('l2tp-modal-defroute').checked = true;
  1842. document.getElementById('l2tp-modal-disabled').checked = false;
  1843. document.getElementById('l2tp-modal').classList.remove('hidden');
  1844. }
  1845. function openEditL2TPModal(name) {
  1846. const inst = (state.l2tpList || []).find(i => i.name === name);
  1847. if (!inst) return;
  1848. document.getElementById('l2tp-modal-title').innerText = `Edit L2TP Client: ${name}`;
  1849. document.getElementById('l2tp-modal-name').value = inst.name;
  1850. document.getElementById('l2tp-modal-name').readOnly = true;
  1851. document.getElementById('l2tp-modal-server').value = inst.connect_to || '';
  1852. document.getElementById('l2tp-modal-user').value = inst.username || '';
  1853. document.getElementById('l2tp-modal-pass').value = inst.password || '';
  1854. document.getElementById('l2tp-modal-ipsec').value = inst.ipsec_secret || '';
  1855. document.getElementById('l2tp-modal-defroute').checked = inst.default_route ?? true;
  1856. document.getElementById('l2tp-modal-disabled').checked = !!inst.disabled;
  1857. document.getElementById('l2tp-modal').classList.remove('hidden');
  1858. }
  1859. function closeL2TPModal() {
  1860. document.getElementById('l2tp-modal').classList.add('hidden');
  1861. }
  1862. async function submitSaveL2TP(e) {
  1863. e.preventDefault();
  1864. const name = document.getElementById('l2tp-modal-name').value.trim();
  1865. const server = document.getElementById('l2tp-modal-server').value.trim();
  1866. const user = document.getElementById('l2tp-modal-user').value.trim();
  1867. const pass = document.getElementById('l2tp-modal-pass').value;
  1868. const ipsec = document.getElementById('l2tp-modal-ipsec').value;
  1869. const defRoute = document.getElementById('l2tp-modal-defroute').checked;
  1870. const disabled = document.getElementById('l2tp-modal-disabled').checked;
  1871. try {
  1872. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`, {
  1873. method: 'POST',
  1874. headers: { 'Content-Type': 'application/json' },
  1875. body: JSON.stringify({
  1876. name,
  1877. connect_to: server,
  1878. username: user,
  1879. password: pass,
  1880. ipsec_secret: ipsec,
  1881. default_route: defRoute,
  1882. disabled
  1883. })
  1884. });
  1885. if (res.ok) {
  1886. showToast('L2TP Saved', `Client ${name} configuration saved`, 'success');
  1887. closeL2TPModal();
  1888. loadL2TP(false);
  1889. fetchData(false);
  1890. }
  1891. } catch (err) {
  1892. showToast('Error', err.message, 'error');
  1893. }
  1894. }
  1895. async function connectL2TPInstance(name) {
  1896. try {
  1897. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1898. if (res.ok) {
  1899. showToast('Connecting', `Dialing L2TP ${name}...`, 'info');
  1900. setTimeout(() => loadL2TP(false), 2000);
  1901. }
  1902. } catch (err) {
  1903. showToast('Error', err.message, 'error');
  1904. }
  1905. }
  1906. async function disconnectL2TPInstance(name) {
  1907. try {
  1908. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1909. if (res.ok) {
  1910. showToast('Disconnected', `L2TP tunnel ${name} terminated`, 'info');
  1911. loadL2TP(false);
  1912. }
  1913. } catch (err) {
  1914. showToast('Error', err.message, 'error');
  1915. }
  1916. }
  1917. async function toggleL2TPState(name, enable) {
  1918. try {
  1919. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/state`, {
  1920. method: 'POST',
  1921. headers: { 'Content-Type': 'application/json' },
  1922. body: JSON.stringify({ enabled: enable })
  1923. });
  1924. if (res.ok) {
  1925. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1926. loadL2TP(false);
  1927. }
  1928. } catch (err) {
  1929. showToast('Error', err.message, 'error');
  1930. }
  1931. }
  1932. async function deleteL2TPInstance(name) {
  1933. if (!confirm(`Are you sure you want to delete L2TP client ${name}?`)) return;
  1934. try {
  1935. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1936. if (res.ok) {
  1937. showToast('Deleted', `L2TP client ${name} removed`, 'success');
  1938. loadL2TP(false);
  1939. fetchData(false);
  1940. }
  1941. } catch (err) {
  1942. showToast('Error', err.message, 'error');
  1943. }
  1944. }
  1945. // ======================== PPTP Multi-Instance ========================
  1946. async function loadPPTP(populateInputs = true) {
  1947. try {
  1948. const res = await fetch(`${API_BASE}/vpn/pptp/clients`);
  1949. const list = await res.json();
  1950. state.pptpList = Array.isArray(list) ? list : [];
  1951. const badge = document.getElementById('pptp-count-badge');
  1952. if (badge) badge.innerText = `${state.pptpList.length} Client${state.pptpList.length !== 1 ? 's' : ''}`;
  1953. const tbody = document.getElementById('pptp-table-body');
  1954. const empty = document.getElementById('pptp-empty');
  1955. if (!tbody) return;
  1956. tbody.innerHTML = '';
  1957. if (state.pptpList.length === 0) {
  1958. if (empty) empty.classList.remove('hidden');
  1959. } else {
  1960. if (empty) empty.classList.add('hidden');
  1961. state.pptpList.forEach(inst => {
  1962. const tr = document.createElement('tr');
  1963. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1964. tr.innerHTML = `
  1965. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1966. <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
  1967. <td class="py-2.5 px-3 text-purple-400 font-mono">${inst.connect_to}</td>
  1968. <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
  1969. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
  1970. <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
  1971. <td class="py-2.5 px-3 text-center">
  1972. <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'}">
  1973. ${inst.require_mppe ? 'MPPE-128' : 'None'}
  1974. </span>
  1975. </td>
  1976. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1977. ${inst.running ? `
  1978. <button onclick="disconnectPPTPInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1979. ` : `
  1980. <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>
  1981. `}
  1982. <button onclick="togglePPTPState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1983. ${inst.disabled ? 'Enable' : 'Disable'}
  1984. </button>
  1985. <button onclick="openEditPPTPModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1986. <button onclick="deletePPTPInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1987. </td>
  1988. `;
  1989. tbody.appendChild(tr);
  1990. });
  1991. }
  1992. } catch (err) {
  1993. console.error('Failed to load PPTP:', err);
  1994. }
  1995. }
  1996. function openAddPPTPModal() {
  1997. document.getElementById('pptp-modal-title').innerText = 'Add PPTP Client Interface';
  1998. document.getElementById('pptp-modal-name').value = `pptp-out${(state.pptpList || []).length + 1}`;
  1999. document.getElementById('pptp-modal-name').readOnly = false;
  2000. document.getElementById('pptp-modal-server').value = '';
  2001. document.getElementById('pptp-modal-user').value = '';
  2002. document.getElementById('pptp-modal-pass').value = '';
  2003. document.getElementById('pptp-modal-mppe').checked = true;
  2004. document.getElementById('pptp-modal-defroute').checked = true;
  2005. document.getElementById('pptp-modal-disabled').checked = false;
  2006. document.getElementById('pptp-modal').classList.remove('hidden');
  2007. }
  2008. function openEditPPTPModal(name) {
  2009. const inst = (state.pptpList || []).find(i => i.name === name);
  2010. if (!inst) return;
  2011. document.getElementById('pptp-modal-title').innerText = `Edit PPTP Client: ${name}`;
  2012. document.getElementById('pptp-modal-name').value = inst.name;
  2013. document.getElementById('pptp-modal-name').readOnly = true;
  2014. document.getElementById('pptp-modal-server').value = inst.connect_to || '';
  2015. document.getElementById('pptp-modal-user').value = inst.username || '';
  2016. document.getElementById('pptp-modal-pass').value = inst.password || '';
  2017. document.getElementById('pptp-modal-mppe').checked = inst.require_mppe ?? true;
  2018. document.getElementById('pptp-modal-defroute').checked = inst.default_route ?? true;
  2019. document.getElementById('pptp-modal-disabled').checked = !!inst.disabled;
  2020. document.getElementById('pptp-modal').classList.remove('hidden');
  2021. }
  2022. function closePPTPModal() {
  2023. document.getElementById('pptp-modal').classList.add('hidden');
  2024. }
  2025. async function submitSavePPTP(e) {
  2026. e.preventDefault();
  2027. const name = document.getElementById('pptp-modal-name').value.trim();
  2028. const server = document.getElementById('pptp-modal-server').value.trim();
  2029. const user = document.getElementById('pptp-modal-user').value.trim();
  2030. const pass = document.getElementById('pptp-modal-pass').value;
  2031. const mppe = document.getElementById('pptp-modal-mppe').checked;
  2032. const defRoute = document.getElementById('pptp-modal-defroute').checked;
  2033. const disabled = document.getElementById('pptp-modal-disabled').checked;
  2034. try {
  2035. const res = await fetch(`${API_BASE}/vpn/pptp/clients`, {
  2036. method: 'POST',
  2037. headers: { 'Content-Type': 'application/json' },
  2038. body: JSON.stringify({
  2039. name,
  2040. connect_to: server,
  2041. username: user,
  2042. password: pass,
  2043. require_mppe: mppe,
  2044. default_route: defRoute,
  2045. auto_reconnect: true,
  2046. disabled
  2047. })
  2048. });
  2049. if (res.ok) {
  2050. showToast('PPTP Saved', `Client ${name} configuration saved`, 'success');
  2051. closePPTPModal();
  2052. loadPPTP(false);
  2053. fetchData(false);
  2054. }
  2055. } catch (err) {
  2056. showToast('Error', err.message, 'error');
  2057. }
  2058. }
  2059. async function connectPPTPInstance(name) {
  2060. try {
  2061. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2062. if (res.ok) {
  2063. showToast('Connecting', `Dialing PPTP ${name}...`, 'info');
  2064. setTimeout(() => loadPPTP(false), 2000);
  2065. }
  2066. } catch (err) {
  2067. showToast('Error', err.message, 'error');
  2068. }
  2069. }
  2070. async function disconnectPPTPInstance(name) {
  2071. try {
  2072. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2073. if (res.ok) {
  2074. showToast('Disconnected', `PPTP tunnel ${name} terminated`, 'info');
  2075. loadPPTP(false);
  2076. }
  2077. } catch (err) {
  2078. showToast('Error', err.message, 'error');
  2079. }
  2080. }
  2081. async function togglePPTPState(name, enable) {
  2082. try {
  2083. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/state`, {
  2084. method: 'POST',
  2085. headers: { 'Content-Type': 'application/json' },
  2086. body: JSON.stringify({ enabled: enable })
  2087. });
  2088. if (res.ok) {
  2089. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2090. loadPPTP(false);
  2091. }
  2092. } catch (err) {
  2093. showToast('Error', err.message, 'error');
  2094. }
  2095. }
  2096. async function deletePPTPInstance(name) {
  2097. if (!confirm(`Are you sure you want to delete PPTP client ${name}?`)) return;
  2098. try {
  2099. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2100. if (res.ok) {
  2101. showToast('Deleted', `PPTP client ${name} removed`, 'success');
  2102. loadPPTP(false);
  2103. fetchData(false);
  2104. }
  2105. } catch (err) {
  2106. showToast('Error', err.message, 'error');
  2107. }
  2108. }
  2109. // ---------------- Modal & Helper Functions ----------------
  2110. function openVlanModal(defaultParent = '') {
  2111. const select = document.getElementById('vlan-parent');
  2112. select.innerHTML = '';
  2113. const allIfaces = state.interfaces || [];
  2114. const eligible = allIfaces.filter(i => supportsVLAN(i));
  2115. if (eligible.length === 0) {
  2116. const opt = document.createElement('option');
  2117. opt.value = '';
  2118. opt.innerText = 'No VLAN-capable interfaces available';
  2119. select.appendChild(opt);
  2120. } else {
  2121. eligible.forEach(i => {
  2122. const opt = document.createElement('option');
  2123. opt.value = i.name;
  2124. opt.innerText = `${i.name} (${i.role || i.type || 'Ethernet'} - ${i.state})`;
  2125. if (i.name === defaultParent) opt.selected = true;
  2126. select.appendChild(opt);
  2127. });
  2128. }
  2129. document.getElementById('vlan-id').value = '';
  2130. document.getElementById('vlan-name').value = '';
  2131. document.getElementById('vlan-ip').value = '';
  2132. document.getElementById('vlan-desc').value = '';
  2133. autoSuggestVlanName();
  2134. document.getElementById('vlan-modal').classList.remove('hidden');
  2135. }
  2136. function closeVlanModal() {
  2137. document.getElementById('vlan-modal').classList.add('hidden');
  2138. }
  2139. function autoSuggestVlanName() {
  2140. const parent = document.getElementById('vlan-parent').value;
  2141. if (!parent) return;
  2142. const id = document.getElementById('vlan-id').value;
  2143. const nameInput = document.getElementById('vlan-name');
  2144. if (parent && id) nameInput.placeholder = `${parent}.${id}`;
  2145. }
  2146. function setSubnetPreset(cidr) {
  2147. const ipInput = document.getElementById('vlan-ip');
  2148. const id = document.getElementById('vlan-id').value || '10';
  2149. ipInput.value = `192.168.${id}.1${cidr}`;
  2150. }
  2151. async function submitCreateVlan(e) {
  2152. e.preventDefault();
  2153. const btn = document.getElementById('vlan-submit-btn');
  2154. btn.disabled = true;
  2155. btn.innerText = 'Creating...';
  2156. const parent = document.getElementById('vlan-parent').value;
  2157. if (!parent) {
  2158. showToast('Error', 'Please select a valid VLAN-capable parent interface', 'error');
  2159. btn.disabled = false;
  2160. btn.innerText = 'Create VLAN';
  2161. return;
  2162. }
  2163. const id = parseInt(document.getElementById('vlan-id').value, 10);
  2164. const name = document.getElementById('vlan-name').value.trim();
  2165. const ip = document.getElementById('vlan-ip').value.trim();
  2166. const role = document.getElementById('vlan-role').value;
  2167. const desc = document.getElementById('vlan-desc').value.trim();
  2168. try {
  2169. const res = await fetch(`${API_BASE}/vlans`, {
  2170. method: 'POST',
  2171. headers: { 'Content-Type': 'application/json' },
  2172. body: JSON.stringify({
  2173. parent_name: parent,
  2174. vlan_id: id,
  2175. name: name,
  2176. ip_address: ip,
  2177. role: role,
  2178. description: desc,
  2179. mtu: 1500,
  2180. auto_up: true
  2181. })
  2182. });
  2183. const data = await res.json();
  2184. if (res.ok) {
  2185. showToast('VLAN Created', `Created ${data.name} (VLAN ${data.vlan_id})`, 'success');
  2186. state.expandedParents.add(parent);
  2187. closeVlanModal();
  2188. await fetchData(true);
  2189. if (state.activeTab !== 'interfaces') navigate('interfaces');
  2190. } else {
  2191. showToast('Creation Failed', data.message || 'Failed to create VLAN', 'error');
  2192. }
  2193. } catch (err) {
  2194. showToast('Error', err.message, 'error');
  2195. } finally {
  2196. btn.disabled = false;
  2197. btn.innerText = 'Create VLAN';
  2198. }
  2199. }
  2200. async function confirmDeleteVlan(name) {
  2201. if (!confirm(`Delete VLAN interface ${name}?`)) return;
  2202. try {
  2203. const res = await fetch(`${API_BASE}/vlans/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2204. if (res.ok) {
  2205. showToast('VLAN Deleted', `Interface ${name} removed`, 'success');
  2206. closeIfaceModal();
  2207. fetchData(true);
  2208. }
  2209. } catch (err) {
  2210. showToast('Error', err.message, 'error');
  2211. }
  2212. }
  2213. function openIfaceModal(name) {
  2214. const iface = (state.interfaces || []).find(i => i.name === name);
  2215. if (!iface) return;
  2216. state.currentModalIface = iface.name;
  2217. document.getElementById('modal-iface-name').innerText = iface.name;
  2218. document.getElementById('modal-iface-badge').innerText = iface.is_vlan ? `VLAN ${iface.vlan_id}` : iface.type;
  2219. document.getElementById('modal-iface-mtu').value = iface.mtu;
  2220. document.getElementById('modal-iface-role').value = iface.role || 'LAN';
  2221. document.getElementById('modal-iface-desc').value = iface.description || '';
  2222. const delBtn = document.getElementById('modal-delete-vlan-btn');
  2223. if (iface.is_vlan) {
  2224. delBtn.classList.remove('hidden');
  2225. } else {
  2226. delBtn.classList.add('hidden');
  2227. }
  2228. renderModalIPs(iface);
  2229. document.getElementById('iface-modal').classList.remove('hidden');
  2230. }
  2231. function renderModalIPs(iface) {
  2232. const container = document.getElementById('modal-ip-list');
  2233. container.innerHTML = '';
  2234. const addrs = [...(iface.ipv4 || []), ...(iface.ipv6 || [])];
  2235. if (addrs.length === 0) {
  2236. container.innerHTML = `<span class="text-slate-500 text-xs font-sans">No IP addresses currently bound</span>`;
  2237. return;
  2238. }
  2239. addrs.forEach(addr => {
  2240. const row = document.createElement('div');
  2241. row.className = 'flex items-center justify-between p-2 rounded bg-slate-900 border border-slate-800';
  2242. row.innerHTML = `
  2243. <span class="text-white">${addr}</span>
  2244. <button onclick="removeInterfaceIP('${addr}')" class="text-[11px] text-rose-400 hover:text-rose-300 font-sans">Remove</button>
  2245. `;
  2246. container.appendChild(row);
  2247. });
  2248. }
  2249. function closeIfaceModal() {
  2250. document.getElementById('iface-modal').classList.add('hidden');
  2251. state.currentModalIface = null;
  2252. }
  2253. async function setIfaceState(name, newState) {
  2254. await toggleInterfaceState(name, newState);
  2255. const updated = (state.interfaces || []).find(i => i.name === name);
  2256. if (updated) openIfaceModal(name);
  2257. }
  2258. async function applyMTU() {
  2259. const mtu = parseInt(document.getElementById('modal-iface-mtu').value, 10);
  2260. try {
  2261. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/mtu`, {
  2262. method: 'POST',
  2263. headers: { 'Content-Type': 'application/json' },
  2264. body: JSON.stringify({ mtu })
  2265. });
  2266. if (res.ok) {
  2267. showToast('MTU Applied', `Set MTU to ${mtu} on ${state.currentModalIface}`, 'success');
  2268. fetchData(false);
  2269. }
  2270. } catch (err) {
  2271. showToast('Error', err.message, 'error');
  2272. }
  2273. }
  2274. async function addInterfaceIP() {
  2275. const ip = document.getElementById('modal-new-ip').value.trim();
  2276. if (!ip) return;
  2277. try {
  2278. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  2279. method: 'POST',
  2280. headers: { 'Content-Type': 'application/json' },
  2281. body: JSON.stringify({ ip })
  2282. });
  2283. if (res.ok) {
  2284. showToast('IP Added', `Bound ${ip} to ${state.currentModalIface}`, 'success');
  2285. document.getElementById('modal-new-ip').value = '';
  2286. await fetchData(false);
  2287. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  2288. if (iface) renderModalIPs(iface);
  2289. } else {
  2290. const err = await res.json();
  2291. showToast('Error', err.error || err.message || 'Failed to add IP address', 'error');
  2292. }
  2293. } catch (err) {
  2294. showToast('Error', err.message, 'error');
  2295. }
  2296. }
  2297. async function removeInterfaceIP(ip) {
  2298. if (!confirm(`Remove IP ${ip}?`)) return;
  2299. try {
  2300. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  2301. method: 'DELETE',
  2302. headers: { 'Content-Type': 'application/json' },
  2303. body: JSON.stringify({ ip })
  2304. });
  2305. if (res.ok) {
  2306. showToast('IP Removed', `Removed ${ip}`, 'success');
  2307. await fetchData(false);
  2308. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  2309. if (iface) renderModalIPs(iface);
  2310. }
  2311. } catch (err) {
  2312. showToast('Error', err.message, 'error');
  2313. }
  2314. }
  2315. async function saveInterfaceMetadata() {
  2316. const role = document.getElementById('modal-iface-role').value;
  2317. const desc = document.getElementById('modal-iface-desc').value.trim();
  2318. try {
  2319. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/metadata`, {
  2320. method: 'POST',
  2321. headers: { 'Content-Type': 'application/json' },
  2322. body: JSON.stringify({ role, description: desc })
  2323. });
  2324. if (res.ok) {
  2325. showToast('Saved', 'Metadata updated', 'success');
  2326. closeIfaceModal();
  2327. fetchData(false);
  2328. }
  2329. } catch (err) {
  2330. showToast('Error', err.message, 'error');
  2331. }
  2332. }
  2333. // ======================== MIKROTIK FIREWALL (/ip firewall) ========================
  2334. state.fwSubTab = 'filter';
  2335. state.routesSubTab = 'routes';
  2336. function renderRuleFlag(disabled, hasComment) {
  2337. let flags = '';
  2338. if (disabled) flags += '<span class="text-rose-400 font-bold" title="Disabled">X</span>';
  2339. if (hasComment) flags += '<span class="text-amber-400 font-bold ml-1" title="Has Comment">C</span>';
  2340. return flags || '<span class="text-slate-600">-</span>';
  2341. }
  2342. function renderActionBadge(action) {
  2343. const act = (action || '').toLowerCase();
  2344. let color = 'bg-slate-800 text-slate-300';
  2345. if (act === 'accept') color = 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30';
  2346. else if (act === 'drop' || act === 'reject') color = 'bg-rose-500/20 text-rose-300 border border-rose-500/30';
  2347. else if (act === 'masquerade' || act === 'src-nat' || act === 'dst-nat') color = 'bg-amber-500/20 text-amber-300 border border-amber-500/30';
  2348. else if (act.startsWith('mark-')) color = 'bg-purple-500/20 text-purple-300 border border-purple-500/30';
  2349. else if (act === 'log') color = 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30';
  2350. return `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold ${color}">${action}</span>`;
  2351. }
  2352. function switchFWSubTab(tab) {
  2353. state.fwSubTab = tab;
  2354. const tabs = ['filter', 'nat', 'mangle', 'addrlist', 'geo', 'connections'];
  2355. tabs.forEach(t => {
  2356. const panel = document.getElementById(`fw-subtab-${t}`);
  2357. const btn = document.getElementById(`fw-subtab-btn-${t}`);
  2358. if (panel) {
  2359. if (t === tab) panel.classList.remove('hidden');
  2360. else panel.classList.add('hidden');
  2361. }
  2362. if (btn) {
  2363. if (t === tab) {
  2364. 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';
  2365. } else {
  2366. 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';
  2367. }
  2368. }
  2369. });
  2370. const addBtn = document.getElementById('fw-primary-add-btn');
  2371. if (addBtn) {
  2372. if (tab === 'filter') addBtn.innerHTML = '<span>+ Add Filter Rule</span>';
  2373. else if (tab === 'nat') addBtn.innerHTML = '<span>+ Add NAT Rule</span>';
  2374. else if (tab === 'mangle') addBtn.innerHTML = '<span>+ Add Mangle Rule</span>';
  2375. else if (tab === 'addrlist') addBtn.innerHTML = '<span>+ Add Address List</span>';
  2376. else if (tab === 'geo') addBtn.innerHTML = '<span>⚙️ Schedule Settings</span>';
  2377. else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
  2378. }
  2379. if (tab === 'geo') loadGeoIP();
  2380. if (tab === 'connections') loadConnections();
  2381. setTimeout(initTableSorting, 50);
  2382. }
  2383. function openCurrentFWModal() {
  2384. if (state.fwSubTab === 'filter') openAddFilterModal();
  2385. else if (state.fwSubTab === 'nat') openAddNATModal();
  2386. else if (state.fwSubTab === 'mangle') openAddMangleModal();
  2387. else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
  2388. else if (state.fwSubTab === 'geo') openGeoIntervalModal();
  2389. else if (state.fwSubTab === 'connections') loadConnections();
  2390. }
  2391. async function loadFirewall(populateDropdowns = true) {
  2392. try {
  2393. const [summaryRes, filterRes, natRes, mangleRes, addrlistRes, geoStatusRes, geoCountriesRes] = await Promise.all([
  2394. fetch(`${API_BASE}/firewall/summary`),
  2395. fetch(`${API_BASE}/firewall/filter`),
  2396. fetch(`${API_BASE}/firewall/nat`),
  2397. fetch(`${API_BASE}/firewall/mangle`),
  2398. fetch(`${API_BASE}/firewall/address-lists`),
  2399. fetch(`${API_BASE}/firewall/geoip/status`),
  2400. fetch(`${API_BASE}/firewall/geoip/countries`)
  2401. ]);
  2402. if (summaryRes.ok) state.fwSummary = await summaryRes.json();
  2403. if (filterRes.ok) state.filterRules = await filterRes.json();
  2404. if (natRes.ok) state.natRules = await natRes.json();
  2405. if (mangleRes.ok) state.mangleRules = await mangleRes.json();
  2406. if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
  2407. if (geoStatusRes.ok) state.geoStatus = await geoStatusRes.json();
  2408. if (geoCountriesRes.ok) state.geoCountries = await geoCountriesRes.json();
  2409. // Badges
  2410. const bFilter = document.getElementById('fw-badge-filter');
  2411. if (bFilter) bFilter.innerText = (state.filterRules || []).length;
  2412. const bNat = document.getElementById('fw-badge-nat');
  2413. if (bNat) bNat.innerText = (state.natRules || []).length;
  2414. const bMangle = document.getElementById('fw-badge-mangle');
  2415. if (bMangle) bMangle.innerText = (state.mangleRules || []).length;
  2416. const bAddr = document.getElementById('fw-badge-addrlist');
  2417. if (bAddr) bAddr.innerText = (state.addressLists || []).length;
  2418. const bGeo = document.getElementById('fw-badge-geo');
  2419. if (bGeo) bGeo.innerText = state.geoStatus?.enabled_count || 0;
  2420. renderFilterRules();
  2421. renderNATRules();
  2422. renderMangleRules();
  2423. renderAddressLists();
  2424. renderGeoCountries();
  2425. if (state.fwSubTab === 'connections') {
  2426. loadConnections();
  2427. }
  2428. } catch (err) {
  2429. console.error('Failed to load firewall:', err);
  2430. }
  2431. }
  2432. // ----------------- Filter Rules -----------------
  2433. function renderFilterRules() {
  2434. const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
  2435. const tbody = document.getElementById('filter-table-body');
  2436. const empty = document.getElementById('filter-empty');
  2437. if (!tbody) return;
  2438. tbody.innerHTML = '';
  2439. const rules = (state.filterRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2440. document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
  2441. if (rules.length === 0) {
  2442. empty?.classList.remove('hidden');
  2443. return;
  2444. }
  2445. empty?.classList.add('hidden');
  2446. rules.forEach((r, idx) => {
  2447. const tr = document.createElement('tr');
  2448. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2449. const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
  2450. const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
  2451. let actionExtra = '';
  2452. if (r.action === 'reject') {
  2453. actionExtra = `<span class="block text-[10px] text-rose-300 font-mono mt-0.5">(${r.reject_with || 'icmp-net-unreach'})</span>`;
  2454. } else if (r.action === 'jump') {
  2455. actionExtra = `<span class="block text-[10px] text-yellow-300 font-mono mt-0.5">&rarr; ${r.jump_target || '-'}</span>`;
  2456. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  2457. actionExtra = `<span class="block text-[10px] text-emerald-300 font-mono mt-0.5">&rarr; ${r.address_list || '-'}</span>`;
  2458. } else if (r.action === 'log' && r.log_prefix) {
  2459. actionExtra = `<span class="block text-[10px] text-slate-400 font-mono mt-0.5">${r.log_prefix}</span>`;
  2460. }
  2461. tr.innerHTML = `
  2462. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  2463. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  2464. <td class="py-2.5 px-3 font-bold text-white">${r.chain}</td>
  2465. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  2466. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  2467. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}</td>
  2468. <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
  2469. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  2470. <td class="py-2.5 px-3">${renderActionBadge(r.action)}${actionExtra}</td>
  2471. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2472. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2473. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2474. </td>
  2475. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2476. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2477. <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2478. <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2479. <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>
  2480. <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2481. <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2482. </td>
  2483. `;
  2484. tbody.appendChild(tr);
  2485. });
  2486. }
  2487. function formatTarget(addr, list, geo) {
  2488. const parts = [];
  2489. if (addr) parts.push(`<span>${addr}</span>`);
  2490. if (list) {
  2491. const inv = list.startsWith('!') ? '!' : '';
  2492. const clean = list.replace(/^!/, '');
  2493. 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>`);
  2494. }
  2495. if (geo) {
  2496. const inv = geo.startsWith('!') ? '!' : '';
  2497. const clean = geo.replace(/^!/, '').replace(/^geo:/, '');
  2498. 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>`);
  2499. }
  2500. if (parts.length === 0) return '<span class="text-slate-600">0.0.0.0/0</span>';
  2501. return parts.join(' ');
  2502. }
  2503. function populateInterfaceSelect(selectId, currentVal = '') {
  2504. const sel = document.getElementById(selectId);
  2505. if (!sel) return;
  2506. sel.innerHTML = '<option value="">(Any Interface)</option>';
  2507. (state.interfaces || []).forEach(i => {
  2508. const opt = document.createElement('option');
  2509. opt.value = i.name;
  2510. opt.innerText = `${i.name} (${i.role || i.type})`;
  2511. if (i.name === currentVal) opt.selected = true;
  2512. sel.appendChild(opt);
  2513. });
  2514. }
  2515. function populateAddressListSelect(selectId, currentVal = '') {
  2516. const sel = document.getElementById(selectId);
  2517. if (!sel) return;
  2518. sel.innerHTML = '<option value="">(None)</option>';
  2519. const cleanVal = (currentVal || '').replace(/^!/, '');
  2520. const customNames = Array.from(new Set((state.addressLists || []).map(a => a.name))).sort();
  2521. customNames.forEach(name => {
  2522. const count = (state.addressLists || []).filter(a => a.name === name).length;
  2523. const opt = document.createElement('option');
  2524. opt.value = name;
  2525. opt.innerText = `${name} (${count} entries)`;
  2526. if (name === cleanVal) opt.selected = true;
  2527. sel.appendChild(opt);
  2528. });
  2529. if (cleanVal && !sel.querySelector(`option[value="${cleanVal}"]`)) {
  2530. const opt = document.createElement('option');
  2531. opt.value = cleanVal;
  2532. opt.innerText = cleanVal;
  2533. opt.selected = true;
  2534. sel.appendChild(opt);
  2535. }
  2536. populateCommonAddrListDatalist();
  2537. }
  2538. function populateCommonAddrListDatalist() {
  2539. const dl = document.getElementById('fw-addrlist-datalist');
  2540. if (!dl) return;
  2541. dl.innerHTML = '';
  2542. const names = Array.from(new Set((state.addressLists || []).map(a => a.name).filter(Boolean))).sort();
  2543. names.forEach(name => {
  2544. const opt = document.createElement('option');
  2545. opt.value = name;
  2546. dl.appendChild(opt);
  2547. });
  2548. }
  2549. function populateGeoIPSelect(selectId, currentVal = '') {
  2550. const sel = document.getElementById(selectId);
  2551. if (!sel) return;
  2552. sel.innerHTML = '<option value="">(None)</option>';
  2553. const cleanVal = (currentVal || '').replace(/^!/, '').replace(/^geo:/, '').toUpperCase();
  2554. // Presets optgroup
  2555. const grpPresets = document.createElement('optgroup');
  2556. grpPresets.label = '⚡ Regional Presets';
  2557. const presets = [
  2558. { code: 'EU', label: '🇪🇺 European Union (EU - 27 countries)' },
  2559. { code: 'BALKANS', label: '🏛️ Balkans (GR, CY, BG, RO, AL, etc.)' },
  2560. { code: 'BLOCKLIST', label: '🛡️ High-Risk Blocklist (CN, RU, IR, KP, BY)' }
  2561. ];
  2562. presets.forEach(p => {
  2563. const opt = document.createElement('option');
  2564. opt.value = p.code;
  2565. opt.innerText = p.label;
  2566. if (p.code === cleanVal) opt.selected = true;
  2567. grpPresets.appendChild(opt);
  2568. });
  2569. sel.appendChild(grpPresets);
  2570. // All Countries optgroup
  2571. const grpCountries = document.createElement('optgroup');
  2572. grpCountries.label = '🌍 All Countries';
  2573. const countries = (state.geoCountries || []).slice().sort((a, b) => a.name.localeCompare(b.name));
  2574. countries.forEach(c => {
  2575. const opt = document.createElement('option');
  2576. opt.value = c.code;
  2577. const subnetsInfo = c.subnet_count ? ` [${c.subnet_count.toLocaleString()} subnets]` : '';
  2578. opt.innerText = `${c.name} (${c.code})${subnetsInfo}`;
  2579. if (c.code === cleanVal) opt.selected = true;
  2580. grpCountries.appendChild(opt);
  2581. });
  2582. sel.appendChild(grpCountries);
  2583. }
  2584. // ==================== FIREWALL FILTER MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  2585. function switchFwRuleTab(tab) {
  2586. state.activeFwRuleTab = tab;
  2587. document.querySelectorAll('.fw-rule-tab-btn').forEach(btn => {
  2588. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  2589. btn.classList.add('text-slate-400', 'border-transparent');
  2590. });
  2591. const activeBtn = document.getElementById(`fw-tab-btn-${tab}`);
  2592. if (activeBtn) {
  2593. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  2594. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  2595. }
  2596. document.querySelectorAll('.fw-rule-pane').forEach(p => p.classList.add('hidden'));
  2597. const activePane = document.getElementById(`fw-pane-${tab}`);
  2598. if (activePane) activePane.classList.remove('hidden');
  2599. if (tab === 'statistics') {
  2600. startFwStatPolling();
  2601. } else {
  2602. stopFwStatPolling();
  2603. }
  2604. }
  2605. function toggleFwField(fieldKey, expand) {
  2606. const plusBtn = document.getElementById(`fw-plus-${fieldKey}`);
  2607. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  2608. if (!plusBtn || !fieldBox) return;
  2609. if (expand) {
  2610. plusBtn.classList.add('hidden');
  2611. fieldBox.classList.remove('hidden');
  2612. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  2613. if (valInput) valInput.focus();
  2614. } else {
  2615. fieldBox.classList.add('hidden');
  2616. plusBtn.classList.remove('hidden');
  2617. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  2618. if (valInput) {
  2619. if (valInput.tagName === 'SELECT') {
  2620. valInput.selectedIndex = 0;
  2621. } else {
  2622. valInput.value = '';
  2623. }
  2624. }
  2625. const invInput = document.getElementById(`fw-inv-${fieldKey}`);
  2626. if (invInput) invInput.checked = false;
  2627. if (fieldKey === 'cs') {
  2628. ['filter-modal-cs-established', 'filter-modal-cs-related', 'filter-modal-cs-new', 'filter-modal-cs-invalid', 'filter-modal-cs-untracked'].forEach(id => {
  2629. const el = document.getElementById(id);
  2630. if (el) el.checked = false;
  2631. });
  2632. }
  2633. if (fieldKey === 'natstate') {
  2634. ['filter-modal-nat-srcnat', 'filter-modal-nat-dstnat'].forEach(id => {
  2635. const el = document.getElementById(id);
  2636. if (el) el.checked = false;
  2637. });
  2638. }
  2639. if (fieldKey === 'days') {
  2640. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  2641. const el = document.getElementById(`fw-day-${d}`);
  2642. if (el) el.checked = true;
  2643. });
  2644. }
  2645. }
  2646. }
  2647. function setFwFieldVal(fieldKey, value, hasInvert = false) {
  2648. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  2649. toggleFwField(fieldKey, true);
  2650. let strVal = String(value);
  2651. if (hasInvert) {
  2652. const inv = strVal.startsWith('!');
  2653. if (inv) strVal = strVal.slice(1);
  2654. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  2655. if (invEl) invEl.checked = inv;
  2656. }
  2657. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  2658. if (valEl) valEl.value = strVal;
  2659. } else {
  2660. toggleFwField(fieldKey, false);
  2661. }
  2662. }
  2663. function getFwFieldVal(fieldKey, hasInvert = false) {
  2664. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  2665. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  2666. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  2667. let v = valEl ? valEl.value.trim() : '';
  2668. if (!v) return '';
  2669. if (hasInvert) {
  2670. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  2671. if (invEl && invEl.checked) {
  2672. v = '!' + v.replace(/^!/, '');
  2673. }
  2674. }
  2675. return v;
  2676. }
  2677. function toggleMaximizeFilterModal() {
  2678. const win = document.getElementById('filter-modal-window');
  2679. if (!win) return;
  2680. if (win.classList.contains('max-w-[720px]')) {
  2681. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  2682. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  2683. } else {
  2684. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  2685. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  2686. }
  2687. }
  2688. function openAddFilterModal() {
  2689. switchFwRuleTab('general');
  2690. const badge = document.getElementById('fw-modal-badge');
  2691. if (badge) badge.innerText = 'New...';
  2692. document.getElementById('filter-modal-id').value = '';
  2693. document.getElementById('filter-modal-enabled').checked = true;
  2694. document.getElementById('filter-modal-comment').value = '';
  2695. document.getElementById('filter-modal-chain').value = 'forward';
  2696. document.getElementById('filter-modal-action').value = 'accept';
  2697. document.getElementById('filter-modal-log').checked = false;
  2698. populateInterfaceSelect('fw-val-iniface');
  2699. populateInterfaceSelect('fw-val-outiface');
  2700. populateAddressListSelect('fw-val-srclist');
  2701. populateAddressListSelect('fw-val-dstlist');
  2702. populateGeoIPSelect('fw-val-srcgeo');
  2703. populateGeoIPSelect('fw-val-dstgeo');
  2704. const allFieldKeys = [
  2705. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  2706. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  2707. 'routingmark', 'conntype', 'cs', 'natstate',
  2708. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  2709. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  2710. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  2711. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  2712. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  2713. ];
  2714. allFieldKeys.forEach(k => toggleFwField(k, false));
  2715. resetCurrentRuleCounters();
  2716. toggleFilterActionFields();
  2717. document.getElementById('filter-modal').classList.remove('hidden');
  2718. }
  2719. function openEditFilterModal(id) {
  2720. const r = (state.filterRules || []).find(rule => rule.id === id);
  2721. if (!r) return;
  2722. switchFwRuleTab('general');
  2723. const badge = document.getElementById('fw-modal-badge');
  2724. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  2725. document.getElementById('filter-modal-id').value = r.id;
  2726. document.getElementById('filter-modal-enabled').checked = !r.disabled;
  2727. document.getElementById('filter-modal-comment').value = r.comment || '';
  2728. document.getElementById('filter-modal-chain').value = r.chain || 'forward';
  2729. document.getElementById('filter-modal-action').value = r.action || 'accept';
  2730. document.getElementById('filter-modal-log').checked = !!r.log;
  2731. populateInterfaceSelect('fw-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  2732. populateInterfaceSelect('fw-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  2733. populateAddressListSelect('fw-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  2734. populateAddressListSelect('fw-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  2735. populateGeoIPSelect('fw-val-srcgeo', r.src_geoip || '');
  2736. populateGeoIPSelect('fw-val-dstgeo', r.dst_geoip || '');
  2737. setFwFieldVal('src', r.src_address, true);
  2738. setFwFieldVal('dst', r.dst_address, true);
  2739. setFwFieldVal('srclist', r.src_address_list, true);
  2740. setFwFieldVal('dstlist', r.dst_address_list, true);
  2741. setFwFieldVal('srcgeo', r.src_geoip, true);
  2742. setFwFieldVal('dstgeo', r.dst_geoip, true);
  2743. if (r.protocol && r.protocol !== 'all') {
  2744. setFwFieldVal('proto', r.protocol, true);
  2745. } else {
  2746. toggleFwField('proto', false);
  2747. }
  2748. setFwFieldVal('sport', r.src_port, true);
  2749. setFwFieldVal('dport', r.dst_port, true);
  2750. setFwFieldVal('anyport', r.any_port, true);
  2751. setFwFieldVal('iniface', r.in_interface, true);
  2752. setFwFieldVal('outiface', r.out_interface, true);
  2753. setFwFieldVal('inifacelist', r.in_interface_list, true);
  2754. setFwFieldVal('outifacelist', r.out_interface_list, true);
  2755. setFwFieldVal('pktmark', r.packet_mark, true);
  2756. setFwFieldVal('connmark', r.connection_mark, true);
  2757. setFwFieldVal('routingmark', r.routing_mark, true);
  2758. setFwFieldVal('conntype', r.connection_type, false);
  2759. const states = r.connection_state || [];
  2760. if (states.length > 0) {
  2761. toggleFwField('cs', true);
  2762. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  2763. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  2764. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  2765. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  2766. document.getElementById('filter-modal-cs-untracked').checked = states.includes('untracked');
  2767. } else {
  2768. toggleFwField('cs', false);
  2769. }
  2770. const natStates = r.connection_nat_state || [];
  2771. if (natStates.length > 0) {
  2772. toggleFwField('natstate', true);
  2773. document.getElementById('filter-modal-nat-srcnat').checked = natStates.includes('srcnat');
  2774. document.getElementById('filter-modal-nat-dstnat').checked = natStates.includes('dstnat');
  2775. } else {
  2776. toggleFwField('natstate', false);
  2777. }
  2778. // Advanced tab fields
  2779. setFwFieldVal('layer7', r.layer7_protocol, false);
  2780. setFwFieldVal('content', r.content, false);
  2781. setFwFieldVal('connbytes', r.connection_bytes, false);
  2782. setFwFieldVal('connrate', r.connection_rate, false);
  2783. setFwFieldVal('pcc', r.pcc, false);
  2784. setFwFieldVal('srcmac', r.src_mac_address, true);
  2785. setFwFieldVal('outbridgeport', r.out_bridge_port, false);
  2786. setFwFieldVal('inbridgeport', r.in_bridge_port, false);
  2787. setFwFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  2788. setFwFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  2789. setFwFieldVal('ipsec', r.ipsec_policy, false);
  2790. setFwFieldVal('tlshost', r.tls_host, false);
  2791. setFwFieldVal('ingresspriority', r.ingress_priority, false);
  2792. setFwFieldVal('priority', r.priority, false);
  2793. setFwFieldVal('dscp', r.dscp, false);
  2794. setFwFieldVal('tcpmss', r.tcp_mss, false);
  2795. if (r.tos) {
  2796. const tosEl = document.getElementById('fw-val-tos');
  2797. if (tosEl) tosEl.value = r.tos;
  2798. }
  2799. setFwFieldVal('pktsize', r.packet_size, false);
  2800. setFwFieldVal('random', r.random, false);
  2801. setFwFieldVal('tcpflags', r.tcp_flags, false);
  2802. setFwFieldVal('icmpoptions', r.icmp_options, false);
  2803. setFwFieldVal('ipv4options', r.ipv4_options, false);
  2804. setFwFieldVal('ttl', r.ttl, false);
  2805. // Extra tab fields
  2806. setFwFieldVal('time', r.time, false);
  2807. if (r.days) {
  2808. toggleFwField('days', true);
  2809. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  2810. const chk = document.getElementById(`fw-day-${d}`);
  2811. if (chk) chk.checked = r.days.includes(d);
  2812. });
  2813. } else {
  2814. toggleFwField('days', false);
  2815. }
  2816. setFwFieldVal('limit', r.limit, false);
  2817. setFwFieldVal('dstlimit', r.dst_limit, false);
  2818. setFwFieldVal('psd', r.psd, false);
  2819. // Action fields
  2820. if (r.reject_with) {
  2821. const rwEl = document.getElementById('filter-modal-rejectwith');
  2822. if (rwEl) rwEl.value = r.reject_with;
  2823. }
  2824. if (r.jump_target) {
  2825. const jtEl = document.getElementById('filter-modal-jumptarget');
  2826. if (jtEl) jtEl.value = r.jump_target;
  2827. }
  2828. if (r.address_list) {
  2829. const alEl = document.getElementById('filter-modal-action-addrlist');
  2830. if (alEl) alEl.value = r.address_list;
  2831. }
  2832. if (r.address_list_timeout) {
  2833. const toEl = document.getElementById('filter-modal-action-timeout');
  2834. if (toEl) toEl.value = r.address_list_timeout;
  2835. }
  2836. setFwFieldVal('logprefix', r.log_prefix, false);
  2837. // Statistics
  2838. const bEl = document.getElementById('fw-stat-bytes');
  2839. const pEl = document.getElementById('fw-stat-packets');
  2840. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  2841. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  2842. state.fwLastBytes = r.bytes || 0;
  2843. state.fwLastPackets = r.packets || 0;
  2844. state.fwLastTimestamp = Date.now();
  2845. state.fwStatRateHistory = new Array(30).fill(0);
  2846. state.fwStatPktHistory = new Array(30).fill(0);
  2847. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  2848. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  2849. toggleFilterActionFields();
  2850. document.getElementById('filter-modal').classList.remove('hidden');
  2851. }
  2852. function closeFilterModal() {
  2853. stopFwStatPolling();
  2854. document.getElementById('filter-modal').classList.add('hidden');
  2855. }
  2856. function toggleFilterActionFields() {
  2857. const act = document.getElementById('filter-modal-action')?.value || 'accept';
  2858. const rejectBox = document.getElementById('filter-action-reject-box');
  2859. const jumpBox = document.getElementById('filter-action-jump-box');
  2860. const addrBox = document.getElementById('filter-action-addrlist-box');
  2861. if (rejectBox) {
  2862. if (act === 'reject') rejectBox.classList.remove('hidden');
  2863. else rejectBox.classList.add('hidden');
  2864. }
  2865. if (jumpBox) {
  2866. if (act === 'jump') jumpBox.classList.remove('hidden');
  2867. else jumpBox.classList.add('hidden');
  2868. }
  2869. if (addrBox) {
  2870. if (act === 'add-dst-to-address-list' || act === 'add-src-to-address-list' || act.includes('address-list') || act.includes('address list')) {
  2871. addrBox.classList.remove('hidden');
  2872. } else {
  2873. addrBox.classList.add('hidden');
  2874. }
  2875. }
  2876. if (act === 'log') {
  2877. const logEl = document.getElementById('filter-modal-log');
  2878. if (logEl) logEl.checked = true;
  2879. toggleFwField('logprefix', true);
  2880. }
  2881. }
  2882. function toggleFwLogPrefix() {
  2883. const isLog = document.getElementById('filter-modal-log')?.checked;
  2884. toggleFwField('logprefix', !!isLog);
  2885. }
  2886. function copyFilterRule() {
  2887. document.getElementById('filter-modal-id').value = '';
  2888. const badge = document.getElementById('fw-modal-badge');
  2889. if (badge) badge.innerText = 'New...';
  2890. showToast('Rule Cloned', 'Ready to save as a new rule copy', 'info');
  2891. }
  2892. function resetCurrentRuleCounters() {
  2893. state.fwStatRateHistory = new Array(30).fill(0);
  2894. state.fwStatPktHistory = new Array(30).fill(0);
  2895. state.fwLastBytes = 0;
  2896. state.fwLastPackets = 0;
  2897. state.fwLastTimestamp = Date.now();
  2898. const bEl = document.getElementById('fw-stat-bytes');
  2899. const pEl = document.getElementById('fw-stat-packets');
  2900. const rEl = document.getElementById('fw-stat-rate');
  2901. const prEl = document.getElementById('fw-stat-pktrate');
  2902. if (bEl) bEl.value = '0 B';
  2903. if (pEl) pEl.value = '0';
  2904. if (rEl) rEl.value = '0 bps';
  2905. if (prEl) prEl.value = '0 p/s';
  2906. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  2907. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  2908. showToast('Counters Reset', 'Rule counter display reset to 0', 'info');
  2909. }
  2910. async function resetAllFwCounters() {
  2911. try {
  2912. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  2913. if (res.ok) {
  2914. resetCurrentRuleCounters();
  2915. showToast('All Counters Reset', 'All firewall counters zeroed', 'success');
  2916. loadFirewall(false);
  2917. }
  2918. } catch (err) {
  2919. showToast('Error', err.message, 'error');
  2920. }
  2921. }
  2922. async function applyFilterRule(closeAfter = false) {
  2923. const id = document.getElementById('filter-modal-id').value;
  2924. const chain = document.getElementById('filter-modal-chain').value;
  2925. const action = document.getElementById('filter-modal-action').value;
  2926. const comment = document.getElementById('filter-modal-comment').value.trim();
  2927. const enabled = document.getElementById('filter-modal-enabled').checked;
  2928. const src = getFwFieldVal('src', true);
  2929. const dst = getFwFieldVal('dst', true);
  2930. const srclist = getFwFieldVal('srclist', true);
  2931. const dstlist = getFwFieldVal('dstlist', true);
  2932. const srcgeo = getFwFieldVal('srcgeo', true);
  2933. const dstgeo = getFwFieldVal('dstgeo', true);
  2934. const proto = getFwFieldVal('proto', true);
  2935. const sport = getFwFieldVal('sport', true);
  2936. const dport = getFwFieldVal('dport', true);
  2937. const anyport = getFwFieldVal('anyport', true);
  2938. const iniface = getFwFieldVal('iniface', true);
  2939. const outiface = getFwFieldVal('outiface', true);
  2940. const inifacelist = getFwFieldVal('inifacelist', true);
  2941. const outifacelist = getFwFieldVal('outifacelist', true);
  2942. const pktmark = getFwFieldVal('pktmark', true);
  2943. const connmark = getFwFieldVal('connmark', true);
  2944. const routingmark = getFwFieldVal('routingmark', true);
  2945. const conntype = getFwFieldVal('conntype', false);
  2946. const states = [];
  2947. const csBox = document.getElementById('fw-field-cs');
  2948. if (csBox && !csBox.classList.contains('hidden')) {
  2949. if (document.getElementById('filter-modal-cs-established')?.checked) states.push('established');
  2950. if (document.getElementById('filter-modal-cs-related')?.checked) states.push('related');
  2951. if (document.getElementById('filter-modal-cs-new')?.checked) states.push('new');
  2952. if (document.getElementById('filter-modal-cs-invalid')?.checked) states.push('invalid');
  2953. if (document.getElementById('filter-modal-cs-untracked')?.checked) states.push('untracked');
  2954. }
  2955. const natStates = [];
  2956. const natBox = document.getElementById('fw-field-natstate');
  2957. if (natBox && !natBox.classList.contains('hidden')) {
  2958. if (document.getElementById('filter-modal-nat-srcnat')?.checked) natStates.push('srcnat');
  2959. if (document.getElementById('filter-modal-nat-dstnat')?.checked) natStates.push('dstnat');
  2960. }
  2961. const payload = {
  2962. id,
  2963. chain,
  2964. action,
  2965. protocol: proto || 'all',
  2966. src_address: src,
  2967. dst_address: dst,
  2968. src_port: sport,
  2969. dst_port: dport,
  2970. any_port: anyport,
  2971. in_interface: iniface,
  2972. out_interface: outiface,
  2973. in_interface_list: inifacelist,
  2974. out_interface_list: outifacelist,
  2975. packet_mark: pktmark,
  2976. connection_mark: connmark,
  2977. routing_mark: routingmark,
  2978. connection_type: conntype,
  2979. connection_state: states,
  2980. connection_nat_state: natStates,
  2981. src_address_list: srclist,
  2982. dst_address_list: dstlist,
  2983. src_geoip: srcgeo,
  2984. dst_geoip: dstgeo,
  2985. comment,
  2986. disabled: !enabled,
  2987. // Advanced tab
  2988. layer7_protocol: getFwFieldVal('layer7', false),
  2989. content: getFwFieldVal('content', false),
  2990. connection_bytes: getFwFieldVal('connbytes', false),
  2991. connection_rate: getFwFieldVal('connrate', false),
  2992. pcc: getFwFieldVal('pcc', false),
  2993. src_mac_address: getFwFieldVal('srcmac', true),
  2994. out_bridge_port: getFwFieldVal('outbridgeport', false),
  2995. in_bridge_port: getFwFieldVal('inbridgeport', false),
  2996. in_bridge_port_list: getFwFieldVal('inbridgeportlist', false),
  2997. out_bridge_port_list: getFwFieldVal('outbridgeportlist', false),
  2998. ipsec_policy: getFwFieldVal('ipsec', false),
  2999. tls_host: getFwFieldVal('tlshost', false),
  3000. ingress_priority: getFwFieldVal('ingresspriority', false),
  3001. priority: getFwFieldVal('priority', false),
  3002. dscp: getFwFieldVal('dscp', false),
  3003. tcp_mss: getFwFieldVal('tcpmss', false),
  3004. tos: document.getElementById('fw-val-tos')?.value || '',
  3005. packet_size: getFwFieldVal('pktsize', false),
  3006. random: getFwFieldVal('random', false),
  3007. tcp_flags: getFwFieldVal('tcpflags', false),
  3008. icmp_options: getFwFieldVal('icmpoptions', false),
  3009. ipv4_options: getFwFieldVal('ipv4options', false),
  3010. ttl: getFwFieldVal('ttl', false),
  3011. // Extra tab
  3012. time: getFwFieldVal('time', false),
  3013. limit: getFwFieldVal('limit', false),
  3014. dst_limit: getFwFieldVal('dstlimit', false),
  3015. psd: getFwFieldVal('psd', false),
  3016. // Action tab
  3017. reject_with: action === 'reject' ? (document.getElementById('filter-modal-rejectwith')?.value || '') : '',
  3018. jump_target: action === 'jump' ? (document.getElementById('filter-modal-jumptarget')?.value || '') : '',
  3019. address_list: action.startsWith('add-') ? (document.getElementById('filter-modal-action-addrlist')?.value || '') : '',
  3020. address_list_timeout: action.startsWith('add-') ? (document.getElementById('filter-modal-action-timeout')?.value || '') : '',
  3021. log: document.getElementById('filter-modal-log')?.checked || false,
  3022. log_prefix: getFwFieldVal('logprefix', false)
  3023. };
  3024. try {
  3025. const res = await fetch(`${API_BASE}/firewall/filter`, {
  3026. method: 'POST',
  3027. headers: { 'Content-Type': 'application/json' },
  3028. body: JSON.stringify(payload)
  3029. });
  3030. if (res.ok) {
  3031. const data = await res.json();
  3032. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  3033. loadFirewall(false);
  3034. if (closeAfter) {
  3035. closeFilterModal();
  3036. } else {
  3037. if (data.id) {
  3038. document.getElementById('filter-modal-id').value = data.id;
  3039. const badge = document.getElementById('fw-modal-badge');
  3040. if (badge) badge.innerText = `#${data.id}`;
  3041. }
  3042. }
  3043. } else {
  3044. const err = await res.json();
  3045. showToast('Error', err.message || 'Failed to save rule', 'error');
  3046. }
  3047. } catch (err) {
  3048. showToast('Error', err.message, 'error');
  3049. }
  3050. }
  3051. function submitSaveFilterRule(e) {
  3052. if (e && e.preventDefault) e.preventDefault();
  3053. return applyFilterRule(true);
  3054. }
  3055. function startFwStatPolling() {
  3056. stopFwStatPolling();
  3057. pollRuleStats();
  3058. state.fwStatInterval = setInterval(pollRuleStats, 1000);
  3059. }
  3060. function stopFwStatPolling() {
  3061. if (state.fwStatInterval) {
  3062. clearInterval(state.fwStatInterval);
  3063. state.fwStatInterval = null;
  3064. }
  3065. }
  3066. async function pollRuleStats() {
  3067. const id = document.getElementById('filter-modal-id')?.value;
  3068. if (!id) {
  3069. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory || new Array(30).fill(0), 'bps', 'fw-stat-legend-rate');
  3070. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory || new Array(30).fill(0), 'p/s', 'fw-stat-legend-pktrate');
  3071. return;
  3072. }
  3073. try {
  3074. const res = await fetch(`${API_BASE}/firewall/filter`);
  3075. if (!res.ok) return;
  3076. const rules = await res.json();
  3077. const r = rules.find(x => x.id === id);
  3078. if (!r) return;
  3079. const now = Date.now();
  3080. const dt = Math.max(0.2, (now - (state.fwLastTimestamp || now)) / 1000);
  3081. state.fwLastTimestamp = now;
  3082. const curBytes = r.bytes || 0;
  3083. const curPackets = r.packets || 0;
  3084. const deltaBytes = Math.max(0, curBytes - (state.fwLastBytes || curBytes));
  3085. const deltaPkts = Math.max(0, curPackets - (state.fwLastPackets || curPackets));
  3086. state.fwLastBytes = curBytes;
  3087. state.fwLastPackets = curPackets;
  3088. const rateBps = Math.round((deltaBytes * 8) / dt);
  3089. const ratePkt = Math.round(deltaPkts / dt);
  3090. if (!state.fwStatRateHistory) state.fwStatRateHistory = new Array(30).fill(0);
  3091. if (!state.fwStatPktHistory) state.fwStatPktHistory = new Array(30).fill(0);
  3092. state.fwStatRateHistory.push(rateBps);
  3093. if (state.fwStatRateHistory.length > 30) state.fwStatRateHistory.shift();
  3094. state.fwStatPktHistory.push(ratePkt);
  3095. if (state.fwStatPktHistory.length > 30) state.fwStatPktHistory.shift();
  3096. const bEl = document.getElementById('fw-stat-bytes');
  3097. const pEl = document.getElementById('fw-stat-packets');
  3098. const rEl = document.getElementById('fw-stat-rate');
  3099. const prEl = document.getElementById('fw-stat-pktrate');
  3100. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  3101. if (pEl) pEl.value = curPackets.toLocaleString();
  3102. if (rEl) rEl.value = formatBps(rateBps);
  3103. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  3104. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3105. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3106. } catch (e) {
  3107. console.error('Error polling rule stats', e);
  3108. }
  3109. }
  3110. function formatBps(bps) {
  3111. if (bps >= 1000000000) return (bps / 1000000000).toFixed(1) + ' Gbps';
  3112. if (bps >= 1000000) return (bps / 1000000).toFixed(1) + ' Mbps';
  3113. if (bps >= 1000) return (bps / 1000).toFixed(1) + ' kbps';
  3114. return bps + ' bps';
  3115. }
  3116. function renderFwSparkline(svgId, dataArray, unit, legendId) {
  3117. const svg = document.getElementById(svgId);
  3118. if (!svg) return;
  3119. const w = 500;
  3120. const h = 100;
  3121. const paddingRight = 45;
  3122. const graphWidth = w - paddingRight;
  3123. const maxVal = Math.max(5, ...dataArray);
  3124. const currentVal = dataArray[dataArray.length - 1] || 0;
  3125. const leg = document.getElementById(legendId);
  3126. if (leg) {
  3127. leg.innerText = unit === 'bps' ? formatBps(currentVal) : `${currentVal.toLocaleString()} p/s`;
  3128. }
  3129. let gridLines = '';
  3130. for (let i = 0; i <= 5; i++) {
  3131. const y = 8 + (i * (h - 18) / 5);
  3132. const valAtLevel = Math.round(maxVal * (5 - i) / 5);
  3133. const label = unit === 'bps' ? formatBps(valAtLevel) : `${valAtLevel} p/s`;
  3134. gridLines += `
  3135. <line x1="0" y1="${y.toFixed(1)}" x2="${graphWidth}" y2="${y.toFixed(1)}" stroke="#1e2c3e" stroke-width="1" />
  3136. <text x="${w - 2}" y="${(y + 3).toFixed(1)}" fill="#64748b" font-size="9" font-family="monospace" text-anchor="end">${label}</text>
  3137. `;
  3138. }
  3139. const step = graphWidth / (dataArray.length - 1);
  3140. const points = dataArray.map((val, idx) => {
  3141. const x = idx * step;
  3142. const y = (h - 10) - (val / maxVal) * (h - 20);
  3143. return `${x.toFixed(1)},${y.toFixed(1)}`;
  3144. });
  3145. const polylineStr = points.join(' ');
  3146. const areaPath = `M 0,${h - 10} L ${polylineStr} L ${graphWidth},${h - 10} Z`;
  3147. svg.innerHTML = `
  3148. ${gridLines}
  3149. <path d="${areaPath}" fill="rgba(14, 165, 233, 0.12)" />
  3150. <polyline fill="none" stroke="#38bdf8" stroke-width="1.8" stroke-linejoin="round" points="${polylineStr}" />
  3151. <circle cx="${graphWidth}" cy="${points[points.length - 1].split(',')[1]}" r="3" fill="#38bdf8" />
  3152. `;
  3153. }
  3154. async function moveFilterRule(id, dir) {
  3155. try {
  3156. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  3157. method: 'POST',
  3158. headers: { 'Content-Type': 'application/json' },
  3159. body: JSON.stringify({ direction: dir })
  3160. });
  3161. if (res.ok) loadFirewall(false);
  3162. } catch (err) {
  3163. showToast('Error', err.message, 'error');
  3164. }
  3165. }
  3166. async function toggleFilterRuleState(id, disabled) {
  3167. try {
  3168. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  3169. method: 'POST',
  3170. headers: { 'Content-Type': 'application/json' },
  3171. body: JSON.stringify({ disabled })
  3172. });
  3173. if (res.ok) loadFirewall(false);
  3174. } catch (err) {
  3175. showToast('Error', err.message, 'error');
  3176. }
  3177. }
  3178. async function deleteFilterRule(id) {
  3179. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  3180. try {
  3181. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3182. if (res.ok) {
  3183. showToast('Deleted', 'Filter rule removed', 'success');
  3184. loadFirewall(false);
  3185. }
  3186. } catch (err) {
  3187. showToast('Error', err.message, 'error');
  3188. }
  3189. }
  3190. // ----------------- NAT Rules -----------------
  3191. function renderNATRules() {
  3192. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  3193. const tbody = document.getElementById('nat-table-body');
  3194. const empty = document.getElementById('nat-empty');
  3195. if (!tbody) return;
  3196. tbody.innerHTML = '';
  3197. const rules = (state.natRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  3198. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  3199. if (rules.length === 0) {
  3200. empty?.classList.remove('hidden');
  3201. return;
  3202. }
  3203. empty?.classList.add('hidden');
  3204. rules.forEach((r, idx) => {
  3205. const tr = document.createElement('tr');
  3206. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  3207. let toTarget = '-';
  3208. if (r.action === 'jump') {
  3209. toTarget = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  3210. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  3211. toTarget = `<span class="text-emerald-300 font-mono font-bold">&rarr; ${r.address_list || '-'}</span>`;
  3212. } else if (r.action === 'redirect') {
  3213. toTarget = `<span class="text-amber-300 font-mono font-bold">ports:${r.to_ports || 'all'}</span>`;
  3214. } else if (r.action === 'masquerade') {
  3215. 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>`;
  3216. } else if (r.action === 'log') {
  3217. toTarget = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  3218. } else {
  3219. const parts = [r.to_addresses, r.to_ports].filter(Boolean);
  3220. toTarget = parts.length ? `<span class="text-amber-300 font-mono font-bold">${parts.join(':')}</span>` : '-';
  3221. }
  3222. const ifaces = [r.out_interface ? 'out:' + r.out_interface : '', r.in_interface ? 'in:' + r.in_interface : ''].filter(Boolean).join(' ');
  3223. tr.innerHTML = `
  3224. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  3225. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  3226. <td class="py-2.5 px-3 font-bold text-amber-400">${r.chain}</td>
  3227. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  3228. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  3229. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}${r.dst_port ? ':' + r.dst_port : ''}</td>
  3230. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  3231. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  3232. <td class="py-2.5 px-3 font-mono text-xs">${toTarget}</td>
  3233. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  3234. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  3235. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  3236. </td>
  3237. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  3238. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3239. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  3240. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  3241. <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>
  3242. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3243. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3244. </td>
  3245. `;
  3246. tbody.appendChild(tr);
  3247. });
  3248. }
  3249. // ==================== FIREWALL NAT MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  3250. function switchNATRuleTab(tab) {
  3251. state.activeNATRuleTab = tab;
  3252. document.querySelectorAll('.nat-rule-tab-btn').forEach(btn => {
  3253. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  3254. btn.classList.add('text-slate-400', 'border-transparent');
  3255. });
  3256. const activeBtn = document.getElementById(`nat-tab-btn-${tab}`);
  3257. if (activeBtn) {
  3258. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  3259. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  3260. }
  3261. document.querySelectorAll('.nat-rule-pane').forEach(p => p.classList.add('hidden'));
  3262. const activePane = document.getElementById(`nat-pane-${tab}`);
  3263. if (activePane) activePane.classList.remove('hidden');
  3264. if (tab === 'statistics') {
  3265. startNATStatPolling();
  3266. } else {
  3267. stopNATStatPolling();
  3268. }
  3269. }
  3270. function toggleNATField(fieldKey, expand) {
  3271. const plusBtn = document.getElementById(`nat-plus-${fieldKey}`);
  3272. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  3273. if (!plusBtn || !fieldBox) return;
  3274. if (expand) {
  3275. plusBtn.classList.add('hidden');
  3276. fieldBox.classList.remove('hidden');
  3277. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  3278. if (valInput) valInput.focus();
  3279. } else {
  3280. fieldBox.classList.add('hidden');
  3281. plusBtn.classList.remove('hidden');
  3282. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  3283. if (valInput) {
  3284. if (valInput.tagName === 'SELECT') {
  3285. valInput.selectedIndex = 0;
  3286. } else {
  3287. valInput.value = '';
  3288. }
  3289. }
  3290. const invInput = document.getElementById(`nat-inv-${fieldKey}`);
  3291. if (invInput) invInput.checked = false;
  3292. if (fieldKey === 'days') {
  3293. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3294. const el = document.getElementById(`nat-day-${d}`);
  3295. if (el) el.checked = true;
  3296. });
  3297. }
  3298. }
  3299. }
  3300. function setNATFieldVal(fieldKey, value, hasInvert = false) {
  3301. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  3302. toggleNATField(fieldKey, true);
  3303. let strVal = String(value);
  3304. if (hasInvert) {
  3305. const inv = strVal.startsWith('!');
  3306. if (inv) strVal = strVal.slice(1);
  3307. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  3308. if (invEl) invEl.checked = inv;
  3309. }
  3310. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  3311. if (valEl) valEl.value = strVal;
  3312. } else {
  3313. toggleNATField(fieldKey, false);
  3314. }
  3315. }
  3316. function getNATFieldVal(fieldKey, hasInvert = false) {
  3317. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  3318. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3319. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  3320. let v = valEl ? valEl.value.trim() : '';
  3321. if (!v) return '';
  3322. if (hasInvert) {
  3323. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  3324. if (invEl && invEl.checked) {
  3325. v = '!' + v.replace(/^!/, '');
  3326. }
  3327. }
  3328. return v;
  3329. }
  3330. function toggleMaximizeNATModal() {
  3331. const win = document.getElementById('nat-modal-window');
  3332. if (!win) return;
  3333. if (win.classList.contains('max-w-[720px]')) {
  3334. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3335. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3336. } else {
  3337. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3338. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3339. }
  3340. }
  3341. function handleNATChainChange() {
  3342. const ch = document.getElementById('nat-modal-chain')?.value || 'srcnat';
  3343. const actSel = document.getElementById('nat-modal-action');
  3344. if (actSel) {
  3345. if (ch === 'srcnat' && (actSel.value === 'dst-nat' || actSel.value === 'redirect')) {
  3346. actSel.value = 'masquerade';
  3347. } else if (ch === 'dstnat' && (actSel.value === 'masquerade' || actSel.value === 'src-nat')) {
  3348. actSel.value = 'dst-nat';
  3349. }
  3350. }
  3351. toggleNATActionFields();
  3352. }
  3353. function toggleNATActionFields() {
  3354. const act = document.getElementById('nat-modal-action')?.value || 'masquerade';
  3355. const rowAddr = document.getElementById('nat-row-toaddr');
  3356. const rowPort = document.getElementById('nat-row-toport');
  3357. const jumpBox = document.getElementById('nat-action-jump-box');
  3358. const addrBox = document.getElementById('nat-action-addrlist-box');
  3359. // Hide all dynamic rows first
  3360. if (rowAddr) rowAddr.classList.add('hidden');
  3361. if (rowPort) rowPort.classList.add('hidden');
  3362. if (jumpBox) jumpBox.classList.add('hidden');
  3363. if (addrBox) addrBox.classList.add('hidden');
  3364. if (['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(act)) {
  3365. if (rowAddr) rowAddr.classList.remove('hidden');
  3366. if (rowPort) rowPort.classList.remove('hidden');
  3367. } else if (act === 'redirect' || act === 'masquerade') {
  3368. if (rowPort) rowPort.classList.remove('hidden');
  3369. } else if (act === 'jump') {
  3370. if (jumpBox) jumpBox.classList.remove('hidden');
  3371. } else if (act.includes('address-list') || act.includes('address list')) {
  3372. if (addrBox) addrBox.classList.remove('hidden');
  3373. }
  3374. if (act === 'log') {
  3375. const logEl = document.getElementById('nat-modal-log');
  3376. if (logEl) logEl.checked = true;
  3377. toggleNATField('logprefix', true);
  3378. }
  3379. }
  3380. function toggleNATLogPrefix() {
  3381. const isLog = document.getElementById('nat-modal-log')?.checked;
  3382. toggleNATField('logprefix', !!isLog);
  3383. }
  3384. function openAddNATModal() {
  3385. switchNATRuleTab('general');
  3386. const badge = document.getElementById('nat-modal-badge');
  3387. if (badge) badge.innerText = 'New...';
  3388. document.getElementById('nat-modal-id').value = '';
  3389. document.getElementById('nat-modal-enabled').checked = true;
  3390. document.getElementById('nat-modal-comment').value = '';
  3391. document.getElementById('nat-modal-chain').value = 'srcnat';
  3392. document.getElementById('nat-modal-action').value = 'masquerade';
  3393. document.getElementById('nat-modal-toaddr').value = '';
  3394. document.getElementById('nat-modal-toport').value = '';
  3395. document.getElementById('nat-modal-log').checked = false;
  3396. populateInterfaceSelect('nat-val-iniface');
  3397. populateInterfaceSelect('nat-val-outiface');
  3398. populateAddressListSelect('nat-val-srclist');
  3399. populateAddressListSelect('nat-val-dstlist');
  3400. populateGeoIPSelect('nat-val-srcgeo');
  3401. populateGeoIPSelect('nat-val-dstgeo');
  3402. const allFieldKeys = [
  3403. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  3404. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  3405. 'routingmark', 'conntype',
  3406. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  3407. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  3408. 'ipsec', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  3409. 'pktsize', 'random', 'icmpoptions', 'ipv4options', 'ttl',
  3410. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  3411. ];
  3412. allFieldKeys.forEach(k => toggleNATField(k, false));
  3413. resetCurrentNATRuleCounters();
  3414. toggleNATActionFields();
  3415. document.getElementById('nat-modal').classList.remove('hidden');
  3416. }
  3417. function openEditNATModal(id) {
  3418. const r = (state.natRules || []).find(rule => rule.id === id);
  3419. if (!r) return;
  3420. switchNATRuleTab('general');
  3421. const badge = document.getElementById('nat-modal-badge');
  3422. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  3423. document.getElementById('nat-modal-id').value = r.id;
  3424. document.getElementById('nat-modal-enabled').checked = !r.disabled;
  3425. document.getElementById('nat-modal-comment').value = r.comment || '';
  3426. document.getElementById('nat-modal-chain').value = r.chain || 'srcnat';
  3427. document.getElementById('nat-modal-action').value = r.action || 'masquerade';
  3428. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  3429. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  3430. document.getElementById('nat-modal-log').checked = !!r.log;
  3431. populateInterfaceSelect('nat-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  3432. populateInterfaceSelect('nat-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  3433. populateAddressListSelect('nat-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  3434. populateAddressListSelect('nat-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  3435. populateGeoIPSelect('nat-val-srcgeo', r.src_geoip || '');
  3436. populateGeoIPSelect('nat-val-dstgeo', r.dst_geoip || '');
  3437. setNATFieldVal('src', r.src_address, true);
  3438. setNATFieldVal('dst', r.dst_address, true);
  3439. setNATFieldVal('srclist', r.src_address_list, true);
  3440. setNATFieldVal('dstlist', r.dst_address_list, true);
  3441. setNATFieldVal('srcgeo', r.src_geoip, true);
  3442. setNATFieldVal('dstgeo', r.dst_geoip, true);
  3443. if (r.protocol && r.protocol !== 'all') {
  3444. setNATFieldVal('proto', r.protocol, true);
  3445. } else {
  3446. toggleNATField('proto', false);
  3447. }
  3448. setNATFieldVal('sport', r.src_port, true);
  3449. setNATFieldVal('dport', r.dst_port, true);
  3450. setNATFieldVal('anyport', r.any_port, true);
  3451. setNATFieldVal('iniface', r.in_interface, true);
  3452. setNATFieldVal('outiface', r.out_interface, true);
  3453. setNATFieldVal('inifacelist', r.in_interface_list, true);
  3454. setNATFieldVal('outifacelist', r.out_interface_list, true);
  3455. setNATFieldVal('pktmark', r.packet_mark, true);
  3456. setNATFieldVal('connmark', r.connection_mark, true);
  3457. setNATFieldVal('routingmark', r.routing_mark, true);
  3458. setNATFieldVal('conntype', r.connection_type, false);
  3459. // Advanced tab fields
  3460. setNATFieldVal('layer7', r.layer7_protocol, false);
  3461. setNATFieldVal('content', r.content, false);
  3462. setNATFieldVal('connbytes', r.connection_bytes, false);
  3463. setNATFieldVal('connrate', r.connection_rate, false);
  3464. setNATFieldVal('pcc', r.pcc, false);
  3465. setNATFieldVal('srcmac', r.src_mac_address, true);
  3466. setNATFieldVal('outbridgeport', r.out_bridge_port, false);
  3467. setNATFieldVal('inbridgeport', r.in_bridge_port, false);
  3468. setNATFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  3469. setNATFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  3470. setNATFieldVal('ipsec', r.ipsec_policy, false);
  3471. setNATFieldVal('ingresspriority', r.ingress_priority, false);
  3472. setNATFieldVal('priority', r.priority, false);
  3473. setNATFieldVal('dscp', r.dscp, false);
  3474. setNATFieldVal('tcpmss', r.tcp_mss, false);
  3475. if (r.tos) {
  3476. const tosEl = document.getElementById('nat-val-tos');
  3477. if (tosEl) tosEl.value = r.tos;
  3478. }
  3479. setNATFieldVal('pktsize', r.packet_size, false);
  3480. setNATFieldVal('random', r.random, false);
  3481. setNATFieldVal('icmpoptions', r.icmp_options, false);
  3482. setNATFieldVal('ipv4options', r.ipv4_options, false);
  3483. setNATFieldVal('ttl', r.ttl, false);
  3484. // Extra tab fields
  3485. setNATFieldVal('time', r.time, false);
  3486. if (r.days) {
  3487. toggleNATField('days', true);
  3488. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3489. const chk = document.getElementById(`nat-day-${d}`);
  3490. if (chk) chk.checked = r.days.includes(d);
  3491. });
  3492. } else {
  3493. toggleNATField('days', false);
  3494. }
  3495. setNATFieldVal('limit', r.limit, false);
  3496. setNATFieldVal('dstlimit', r.dst_limit, false);
  3497. setNATFieldVal('psd', r.psd, false);
  3498. // Action fields
  3499. if (r.jump_target) {
  3500. const jtEl = document.getElementById('nat-modal-jumptarget');
  3501. if (jtEl) jtEl.value = r.jump_target;
  3502. }
  3503. if (r.address_list) {
  3504. const alEl = document.getElementById('nat-modal-action-addrlist');
  3505. if (alEl) alEl.value = r.address_list;
  3506. }
  3507. if (r.address_list_timeout) {
  3508. const toEl = document.getElementById('nat-modal-action-timeout');
  3509. if (toEl) toEl.value = r.address_list_timeout;
  3510. }
  3511. setNATFieldVal('logprefix', r.log_prefix, false);
  3512. // Statistics
  3513. const bEl = document.getElementById('nat-stat-bytes');
  3514. const pEl = document.getElementById('nat-stat-packets');
  3515. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  3516. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  3517. state.natLastBytes = r.bytes || 0;
  3518. state.natLastPackets = r.packets || 0;
  3519. state.natLastTimestamp = Date.now();
  3520. state.natStatRateHistory = new Array(30).fill(0);
  3521. state.natStatPktHistory = new Array(30).fill(0);
  3522. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  3523. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  3524. toggleNATActionFields();
  3525. document.getElementById('nat-modal').classList.remove('hidden');
  3526. }
  3527. function closeNATModal() {
  3528. stopNATStatPolling();
  3529. document.getElementById('nat-modal').classList.add('hidden');
  3530. }
  3531. function copyNATRule() {
  3532. document.getElementById('nat-modal-id').value = '';
  3533. const badge = document.getElementById('nat-modal-badge');
  3534. if (badge) badge.innerText = 'New...';
  3535. showToast('Rule Cloned', 'Ready to save as a new NAT rule copy', 'info');
  3536. }
  3537. function resetCurrentNATRuleCounters() {
  3538. state.natStatRateHistory = new Array(30).fill(0);
  3539. state.natStatPktHistory = new Array(30).fill(0);
  3540. state.natLastBytes = 0;
  3541. state.natLastPackets = 0;
  3542. state.natLastTimestamp = Date.now();
  3543. const bEl = document.getElementById('nat-stat-bytes');
  3544. const pEl = document.getElementById('nat-stat-packets');
  3545. const rEl = document.getElementById('nat-stat-rate');
  3546. const prEl = document.getElementById('nat-stat-pktrate');
  3547. if (bEl) bEl.value = '0 B';
  3548. if (pEl) pEl.value = '0';
  3549. if (rEl) rEl.value = '0 bps';
  3550. if (prEl) prEl.value = '0 p/s';
  3551. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  3552. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  3553. showToast('Counters Reset', 'NAT rule counter display reset to 0', 'info');
  3554. }
  3555. async function applyNATRule(closeAfter = false) {
  3556. const id = document.getElementById('nat-modal-id').value;
  3557. const chain = document.getElementById('nat-modal-chain').value;
  3558. const action = document.getElementById('nat-modal-action').value;
  3559. const comment = document.getElementById('nat-modal-comment').value.trim();
  3560. const enabled = document.getElementById('nat-modal-enabled').checked;
  3561. const src = getNATFieldVal('src', true);
  3562. const dst = getNATFieldVal('dst', true);
  3563. const srclist = getNATFieldVal('srclist', true);
  3564. const dstlist = getNATFieldVal('dstlist', true);
  3565. const srcgeo = getNATFieldVal('srcgeo', true);
  3566. const dstgeo = getNATFieldVal('dstgeo', true);
  3567. const proto = getNATFieldVal('proto', true);
  3568. const sport = getNATFieldVal('sport', true);
  3569. const dport = getNATFieldVal('dport', true);
  3570. const anyport = getNATFieldVal('anyport', true);
  3571. const iniface = getNATFieldVal('iniface', true);
  3572. const outiface = getNATFieldVal('outiface', true);
  3573. const inifacelist = getNATFieldVal('inifacelist', true);
  3574. const outifacelist = getNATFieldVal('outifacelist', true);
  3575. const pktmark = getNATFieldVal('pktmark', true);
  3576. const connmark = getNATFieldVal('connmark', true);
  3577. const routingmark = getNATFieldVal('routingmark', true);
  3578. const conntype = getNATFieldVal('conntype', false);
  3579. const usesAddr = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(action);
  3580. const usesPort = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat', 'redirect', 'masquerade'].includes(action);
  3581. const payload = {
  3582. id,
  3583. chain,
  3584. action,
  3585. to_addresses: usesAddr ? (document.getElementById('nat-modal-toaddr')?.value.trim() || '') : '',
  3586. to_ports: usesPort ? (document.getElementById('nat-modal-toport')?.value.trim() || '') : '',
  3587. protocol: proto || 'all',
  3588. src_address: src,
  3589. dst_address: dst,
  3590. src_port: sport,
  3591. dst_port: dport,
  3592. any_port: anyport,
  3593. in_interface: iniface,
  3594. out_interface: outiface,
  3595. in_interface_list: inifacelist,
  3596. out_interface_list: outifacelist,
  3597. packet_mark: pktmark,
  3598. connection_mark: connmark,
  3599. routing_mark: routingmark,
  3600. connection_type: conntype,
  3601. src_address_list: srclist,
  3602. dst_address_list: dstlist,
  3603. src_geoip: srcgeo,
  3604. dst_geoip: dstgeo,
  3605. comment,
  3606. disabled: !enabled,
  3607. // Advanced tab
  3608. layer7_protocol: getNATFieldVal('layer7', false),
  3609. content: getNATFieldVal('content', false),
  3610. connection_bytes: getNATFieldVal('connbytes', false),
  3611. connection_rate: getNATFieldVal('connrate', false),
  3612. pcc: getNATFieldVal('pcc', false),
  3613. src_mac_address: getNATFieldVal('srcmac', true),
  3614. out_bridge_port: getNATFieldVal('outbridgeport', false),
  3615. in_bridge_port: getNATFieldVal('inbridgeport', false),
  3616. in_bridge_port_list: getNATFieldVal('inbridgeportlist', false),
  3617. out_bridge_port_list: getNATFieldVal('outbridgeportlist', false),
  3618. ipsec_policy: getNATFieldVal('ipsec', false),
  3619. ingress_priority: getNATFieldVal('ingresspriority', false),
  3620. priority: getNATFieldVal('priority', false),
  3621. dscp: getNATFieldVal('dscp', false),
  3622. tcp_mss: getNATFieldVal('tcpmss', false),
  3623. tos: document.getElementById('nat-val-tos')?.value || '',
  3624. packet_size: getNATFieldVal('pktsize', false),
  3625. random: getNATFieldVal('random', false),
  3626. icmp_options: getNATFieldVal('icmpoptions', false),
  3627. ipv4_options: getNATFieldVal('ipv4options', false),
  3628. ttl: getNATFieldVal('ttl', false),
  3629. // Extra tab
  3630. time: getNATFieldVal('time', false),
  3631. limit: getNATFieldVal('limit', false),
  3632. dst_limit: getNATFieldVal('dstlimit', false),
  3633. psd: getNATFieldVal('psd', false),
  3634. // Action tab
  3635. jump_target: action === 'jump' ? (document.getElementById('nat-modal-jumptarget')?.value || '') : '',
  3636. address_list: action.includes('address') ? (document.getElementById('nat-modal-action-addrlist')?.value || '') : '',
  3637. address_list_timeout: action.includes('address') ? (document.getElementById('nat-modal-action-timeout')?.value || '') : '',
  3638. log: document.getElementById('nat-modal-log')?.checked || false,
  3639. log_prefix: getNATFieldVal('logprefix', false)
  3640. };
  3641. try {
  3642. const res = await fetch(`${API_BASE}/firewall/nat`, {
  3643. method: 'POST',
  3644. headers: { 'Content-Type': 'application/json' },
  3645. body: JSON.stringify(payload)
  3646. });
  3647. if (res.ok) {
  3648. const data = await res.json();
  3649. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  3650. loadFirewall(false);
  3651. if (closeAfter) {
  3652. closeNATModal();
  3653. } else {
  3654. if (data.id) {
  3655. document.getElementById('nat-modal-id').value = data.id;
  3656. const badge = document.getElementById('nat-modal-badge');
  3657. if (badge) badge.innerText = `#${data.id}`;
  3658. }
  3659. }
  3660. } else {
  3661. const err = await res.json();
  3662. showToast('Error', err.message || 'Failed to save rule', 'error');
  3663. }
  3664. } catch (err) {
  3665. showToast('Error', err.message, 'error');
  3666. }
  3667. }
  3668. function submitSaveNATRule(e) {
  3669. if (e && e.preventDefault) e.preventDefault();
  3670. return applyNATRule(true);
  3671. }
  3672. function startNATStatPolling() {
  3673. stopNATStatPolling();
  3674. pollNATRuleStats();
  3675. state.natStatInterval = setInterval(pollNATRuleStats, 1000);
  3676. }
  3677. function stopNATStatPolling() {
  3678. if (state.natStatInterval) {
  3679. clearInterval(state.natStatInterval);
  3680. state.natStatInterval = null;
  3681. }
  3682. }
  3683. async function pollNATRuleStats() {
  3684. const id = document.getElementById('nat-modal-id')?.value;
  3685. if (!id) {
  3686. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory || new Array(30).fill(0), 'bps', 'nat-stat-legend-rate');
  3687. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory || new Array(30).fill(0), 'p/s', 'nat-stat-legend-pktrate');
  3688. return;
  3689. }
  3690. try {
  3691. const res = await fetch(`${API_BASE}/firewall/nat`);
  3692. if (!res.ok) return;
  3693. const rules = await res.json();
  3694. const r = rules.find(x => x.id === id);
  3695. if (!r) return;
  3696. const now = Date.now();
  3697. const dt = Math.max(0.2, (now - (state.natLastTimestamp || now)) / 1000);
  3698. state.natLastTimestamp = now;
  3699. const curBytes = r.bytes || 0;
  3700. const curPackets = r.packets || 0;
  3701. const deltaBytes = Math.max(0, curBytes - (state.natLastBytes || curBytes));
  3702. const deltaPkts = Math.max(0, curPackets - (state.natLastPackets || curPackets));
  3703. state.natLastBytes = curBytes;
  3704. state.natLastPackets = curPackets;
  3705. const rateBps = Math.round((deltaBytes * 8) / dt);
  3706. const ratePkt = Math.round(deltaPkts / dt);
  3707. if (!state.natStatRateHistory) state.natStatRateHistory = new Array(30).fill(0);
  3708. if (!state.natStatPktHistory) state.natStatPktHistory = new Array(30).fill(0);
  3709. state.natStatRateHistory.push(rateBps);
  3710. if (state.natStatRateHistory.length > 30) state.natStatRateHistory.shift();
  3711. state.natStatPktHistory.push(ratePkt);
  3712. if (state.natStatPktHistory.length > 30) state.natStatPktHistory.shift();
  3713. const bEl = document.getElementById('nat-stat-bytes');
  3714. const pEl = document.getElementById('nat-stat-packets');
  3715. const rEl = document.getElementById('nat-stat-rate');
  3716. const prEl = document.getElementById('nat-stat-pktrate');
  3717. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  3718. if (pEl) pEl.value = curPackets.toLocaleString();
  3719. if (rEl) rEl.value = formatBps(rateBps);
  3720. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  3721. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  3722. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  3723. } catch (e) {
  3724. console.error('Error polling NAT rule stats', e);
  3725. }
  3726. }
  3727. async function moveNATRule(id, dir) {
  3728. try {
  3729. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  3730. method: 'POST',
  3731. headers: { 'Content-Type': 'application/json' },
  3732. body: JSON.stringify({ direction: dir })
  3733. });
  3734. if (res.ok) loadFirewall(false);
  3735. } catch (err) {
  3736. showToast('Error', err.message, 'error');
  3737. }
  3738. }
  3739. async function toggleNATRuleState(id, disabled) {
  3740. try {
  3741. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  3742. method: 'POST',
  3743. headers: { 'Content-Type': 'application/json' },
  3744. body: JSON.stringify({ disabled })
  3745. });
  3746. if (res.ok) loadFirewall(false);
  3747. } catch (err) {
  3748. showToast('Error', err.message, 'error');
  3749. }
  3750. }
  3751. async function deleteNATRule(id) {
  3752. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  3753. try {
  3754. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3755. if (res.ok) {
  3756. showToast('Deleted', 'NAT rule removed', 'success');
  3757. loadFirewall(false);
  3758. }
  3759. } catch (err) {
  3760. showToast('Error', err.message, 'error');
  3761. }
  3762. }
  3763. // ----------------- Mangle Rules -----------------
  3764. function renderMangleRules() {
  3765. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  3766. const tbody = document.getElementById('mangle-table-body');
  3767. const empty = document.getElementById('mangle-empty');
  3768. if (!tbody) return;
  3769. tbody.innerHTML = '';
  3770. const rules = (state.mangleRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  3771. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  3772. if (rules.length === 0) {
  3773. empty?.classList.remove('hidden');
  3774. return;
  3775. }
  3776. empty?.classList.add('hidden');
  3777. rules.forEach((r, idx) => {
  3778. const tr = document.createElement('tr');
  3779. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  3780. let markVal = '<span class="text-slate-500">-</span>';
  3781. if (r.new_connection_mark) markVal = `<span class="text-cyan-300 font-mono font-bold">${r.new_connection_mark}</span>`;
  3782. else if (r.new_routing_mark) markVal = `<span class="text-amber-300 font-mono font-bold">${r.new_routing_mark}</span>`;
  3783. else if (r.new_packet_mark) markVal = `<span class="text-emerald-300 font-mono font-bold">${r.new_packet_mark}</span>`;
  3784. else if (r.new_mss) markVal = `<span class="text-sky-300 font-mono font-bold">mss:${r.new_mss}</span>`;
  3785. else if (r.new_dscp) markVal = `<span class="text-purple-300 font-mono font-bold">dscp:${r.new_dscp}</span>`;
  3786. else if (r.new_ttl) markVal = `<span class="text-blue-300 font-mono font-bold">ttl:${r.new_ttl}</span>`;
  3787. else if (r.new_priority) markVal = `<span class="text-indigo-300 font-mono font-bold">prio:${r.new_priority}</span>`;
  3788. else if (r.route) markVal = `<span class="text-orange-300 font-mono font-bold">route:${r.route}</span>`;
  3789. else if (r.sniff_target) markVal = `<span class="text-pink-300 font-mono font-bold">sniff:${r.sniff_target}</span>`;
  3790. else if (r.action === 'jump') markVal = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  3791. else if (r.action.includes('address-list') || r.action.includes('address list')) markVal = `<span class="text-emerald-300 font-mono font-bold">&rarr; ${r.address_list || '-'}</span>`;
  3792. else if (r.action === 'log') markVal = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  3793. tr.innerHTML = `
  3794. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  3795. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  3796. <td class="py-2.5 px-3 font-bold text-purple-400">${r.chain}</td>
  3797. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  3798. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  3799. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  3800. <td class="py-2.5 px-3 font-mono text-xs">${markVal}</td>
  3801. <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>
  3802. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  3803. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  3804. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  3805. </td>
  3806. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  3807. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3808. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  3809. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  3810. <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>
  3811. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3812. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3813. </td>
  3814. `;
  3815. tbody.appendChild(tr);
  3816. });
  3817. }
  3818. // ==================== FIREWALL MANGLE MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  3819. function switchMangleRuleTab(tab) {
  3820. state.activeMangleRuleTab = tab;
  3821. document.querySelectorAll('.mangle-rule-tab-btn').forEach(btn => {
  3822. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  3823. btn.classList.add('text-slate-400', 'border-transparent');
  3824. });
  3825. const activeBtn = document.getElementById(`mangle-tab-btn-${tab}`);
  3826. if (activeBtn) {
  3827. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  3828. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  3829. }
  3830. document.querySelectorAll('.mangle-rule-pane').forEach(p => p.classList.add('hidden'));
  3831. const activePane = document.getElementById(`mangle-pane-${tab}`);
  3832. if (activePane) activePane.classList.remove('hidden');
  3833. if (tab === 'statistics') {
  3834. startMangleStatPolling();
  3835. } else {
  3836. stopMangleStatPolling();
  3837. }
  3838. }
  3839. function toggleMangleField(fieldKey, expand) {
  3840. const plusBtn = document.getElementById(`mangle-plus-${fieldKey}`);
  3841. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  3842. if (!plusBtn || !fieldBox) return;
  3843. if (expand) {
  3844. plusBtn.classList.add('hidden');
  3845. fieldBox.classList.remove('hidden');
  3846. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  3847. if (valInput) valInput.focus();
  3848. } else {
  3849. fieldBox.classList.add('hidden');
  3850. plusBtn.classList.remove('hidden');
  3851. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  3852. if (valInput) {
  3853. if (valInput.tagName === 'SELECT') {
  3854. valInput.selectedIndex = 0;
  3855. } else {
  3856. valInput.value = '';
  3857. }
  3858. }
  3859. const invInput = document.getElementById(`mangle-inv-${fieldKey}`);
  3860. if (invInput) invInput.checked = false;
  3861. if (fieldKey === 'cs') {
  3862. ['mangle-modal-cs-established', 'mangle-modal-cs-related', 'mangle-modal-cs-new', 'mangle-modal-cs-invalid', 'mangle-modal-cs-untracked'].forEach(id => {
  3863. const el = document.getElementById(id);
  3864. if (el) el.checked = false;
  3865. });
  3866. }
  3867. if (fieldKey === 'natstate') {
  3868. ['mangle-modal-nat-srcnat', 'mangle-modal-nat-dstnat'].forEach(id => {
  3869. const el = document.getElementById(id);
  3870. if (el) el.checked = false;
  3871. });
  3872. }
  3873. }
  3874. }
  3875. function setMangleFieldVal(fieldKey, value, hasInvert = false) {
  3876. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  3877. toggleMangleField(fieldKey, true);
  3878. let strVal = String(value);
  3879. if (hasInvert) {
  3880. const inv = strVal.startsWith('!');
  3881. if (inv) strVal = strVal.slice(1);
  3882. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  3883. if (invEl) invEl.checked = inv;
  3884. }
  3885. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  3886. if (valEl) valEl.value = strVal;
  3887. } else {
  3888. toggleMangleField(fieldKey, false);
  3889. }
  3890. }
  3891. function getMangleFieldVal(fieldKey, hasInvert = false) {
  3892. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  3893. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3894. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  3895. let v = valEl ? valEl.value.trim() : '';
  3896. if (!v) return '';
  3897. if (hasInvert) {
  3898. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  3899. if (invEl && invEl.checked) {
  3900. v = '!' + v.replace(/^!/, '');
  3901. }
  3902. }
  3903. return v;
  3904. }
  3905. function toggleMaximizeMangleModal() {
  3906. const win = document.getElementById('mangle-modal-window');
  3907. if (!win) return;
  3908. if (win.classList.contains('max-w-[720px]')) {
  3909. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3910. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3911. } else {
  3912. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3913. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3914. }
  3915. }
  3916. function toggleMangleActionFields() {
  3917. const act = document.getElementById('mangle-modal-action')?.value || 'mark-connection';
  3918. // Hide all dynamic rows first
  3919. ['newconnmark', 'newroutingmark', 'newpktmark', 'newmss', 'newdscp', 'newttl', 'newpriority', 'route', 'sniff', 'passthrough'].forEach(id => {
  3920. const el = document.getElementById(`mangle-row-${id}`);
  3921. if (el) el.classList.add('hidden');
  3922. });
  3923. const jumpBox = document.getElementById('mangle-action-jump-box');
  3924. const addrBox = document.getElementById('mangle-action-addrlist-box');
  3925. if (jumpBox) jumpBox.classList.add('hidden');
  3926. if (addrBox) addrBox.classList.add('hidden');
  3927. // Activate matching rows
  3928. if (act === 'mark-connection') {
  3929. document.getElementById('mangle-row-newconnmark')?.classList.remove('hidden');
  3930. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  3931. } else if (act === 'mark-routing') {
  3932. document.getElementById('mangle-row-newroutingmark')?.classList.remove('hidden');
  3933. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  3934. } else if (act === 'mark-packet') {
  3935. document.getElementById('mangle-row-newpktmark')?.classList.remove('hidden');
  3936. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  3937. } else if (act === 'change-mss') {
  3938. document.getElementById('mangle-row-newmss')?.classList.remove('hidden');
  3939. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  3940. } else if (act === 'change-dscp') {
  3941. document.getElementById('mangle-row-newdscp')?.classList.remove('hidden');
  3942. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  3943. } else if (act === 'change-ttl') {
  3944. document.getElementById('mangle-row-newttl')?.classList.remove('hidden');
  3945. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  3946. } else if (act === 'set-priority') {
  3947. document.getElementById('mangle-row-newpriority')?.classList.remove('hidden');
  3948. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  3949. } else if (act === 'route') {
  3950. document.getElementById('mangle-row-route')?.classList.remove('hidden');
  3951. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  3952. } else if (act === 'sniff-pc' || act === 'sniff-tzsp') {
  3953. document.getElementById('mangle-row-sniff')?.classList.remove('hidden');
  3954. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  3955. } else if (act === 'clear-df' || act === 'strip-ipv4-options') {
  3956. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  3957. } else if (act === 'jump') {
  3958. if (jumpBox) jumpBox.classList.remove('hidden');
  3959. } else if (act.includes('address-list') || act.includes('address list')) {
  3960. if (addrBox) addrBox.classList.remove('hidden');
  3961. }
  3962. if (act === 'log') {
  3963. const logEl = document.getElementById('mangle-modal-log');
  3964. if (logEl) logEl.checked = true;
  3965. toggleMangleField('logprefix', true);
  3966. }
  3967. }
  3968. function toggleMangleLogPrefix() {
  3969. const isLog = document.getElementById('mangle-modal-log')?.checked;
  3970. toggleMangleField('logprefix', !!isLog);
  3971. }
  3972. const allMangleFieldKeys = [
  3973. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  3974. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  3975. 'routingmark', 'conntype', 'cs', 'natstate',
  3976. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  3977. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  3978. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  3979. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  3980. 'nth', 'connlimit', 'srcaddrtype', 'dstaddrtype', 'hotspot', 'ipfragment',
  3981. 'limit', 'dstlimit', 'time', 'psd', 'logprefix'
  3982. ];
  3983. function openAddMangleModal() {
  3984. switchMangleRuleTab('general');
  3985. const badge = document.getElementById('mangle-modal-badge');
  3986. if (badge) badge.innerText = 'New...';
  3987. document.getElementById('mangle-modal-id').value = '';
  3988. document.getElementById('mangle-modal-enabled').checked = true;
  3989. document.getElementById('mangle-modal-comment').value = '';
  3990. document.getElementById('mangle-modal-chain').value = 'prerouting';
  3991. document.getElementById('mangle-modal-action').value = 'mark-connection';
  3992. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = '';
  3993. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = '';
  3994. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = '';
  3995. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = '';
  3996. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = '';
  3997. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = '';
  3998. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = '';
  3999. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = '';
  4000. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = '';
  4001. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = '';
  4002. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = '';
  4003. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = '';
  4004. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = true;
  4005. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = false;
  4006. populateInterfaceSelect('mangle-val-iniface');
  4007. populateInterfaceSelect('mangle-val-outiface');
  4008. populateAddressListSelect('mangle-val-srclist');
  4009. populateAddressListSelect('mangle-val-dstlist');
  4010. populateGeoIPSelect('mangle-val-srcgeo');
  4011. populateGeoIPSelect('mangle-val-dstgeo');
  4012. allMangleFieldKeys.forEach(k => toggleMangleField(k, false));
  4013. resetCurrentMangleRuleCounters();
  4014. toggleMangleActionFields();
  4015. document.getElementById('mangle-modal').classList.remove('hidden');
  4016. }
  4017. function openEditMangleModal(id) {
  4018. const r = (state.mangleRules || []).find(rule => rule.id === id);
  4019. if (!r) return;
  4020. switchMangleRuleTab('general');
  4021. const badge = document.getElementById('mangle-modal-badge');
  4022. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4023. document.getElementById('mangle-modal-id').value = r.id;
  4024. document.getElementById('mangle-modal-enabled').checked = !r.disabled;
  4025. document.getElementById('mangle-modal-comment').value = r.comment || '';
  4026. document.getElementById('mangle-modal-chain').value = r.chain || 'prerouting';
  4027. document.getElementById('mangle-modal-action').value = r.action || 'mark-connection';
  4028. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = r.new_connection_mark || '';
  4029. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = r.new_routing_mark || '';
  4030. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = r.new_packet_mark || '';
  4031. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = r.new_mss || '';
  4032. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = r.new_dscp != null ? r.new_dscp : '';
  4033. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = r.new_ttl || '';
  4034. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = r.new_priority || '';
  4035. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = r.route || '';
  4036. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = r.sniff_target || '';
  4037. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = r.jump_target || '';
  4038. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = r.address_list || '';
  4039. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = r.address_list_timeout || '';
  4040. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  4041. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = !!r.log;
  4042. populateInterfaceSelect('mangle-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  4043. populateInterfaceSelect('mangle-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  4044. populateAddressListSelect('mangle-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  4045. populateAddressListSelect('mangle-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  4046. populateGeoIPSelect('mangle-val-srcgeo', r.src_geoip || '');
  4047. populateGeoIPSelect('mangle-val-dstgeo', r.dst_geoip || '');
  4048. setMangleFieldVal('src', r.src_address, true);
  4049. setMangleFieldVal('dst', r.dst_address, true);
  4050. setMangleFieldVal('srclist', r.src_address_list, true);
  4051. setMangleFieldVal('dstlist', r.dst_address_list, true);
  4052. setMangleFieldVal('srcgeo', r.src_geoip, true);
  4053. setMangleFieldVal('dstgeo', r.dst_geoip, true);
  4054. if (r.protocol && r.protocol !== 'all') {
  4055. setMangleFieldVal('proto', r.protocol, true);
  4056. } else {
  4057. toggleMangleField('proto', false);
  4058. }
  4059. setMangleFieldVal('sport', r.src_port, true);
  4060. setMangleFieldVal('dport', r.dst_port, true);
  4061. setMangleFieldVal('anyport', r.any_port, true);
  4062. setMangleFieldVal('iniface', r.in_interface, true);
  4063. setMangleFieldVal('outiface', r.out_interface, true);
  4064. setMangleFieldVal('inifacelist', r.in_interface_list, true);
  4065. setMangleFieldVal('outifacelist', r.out_interface_list, true);
  4066. setMangleFieldVal('pktmark', r.packet_mark, true);
  4067. setMangleFieldVal('connmark', r.connection_mark, true);
  4068. setMangleFieldVal('routingmark', r.routing_mark, true);
  4069. setMangleFieldVal('conntype', r.connection_type, false);
  4070. // Connection State
  4071. const states = r.connection_state || [];
  4072. if (states.length > 0) {
  4073. toggleMangleField('cs', true);
  4074. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  4075. const el = document.getElementById(`mangle-modal-cs-${s}`);
  4076. if (el) el.checked = states.includes(s);
  4077. });
  4078. } else {
  4079. toggleMangleField('cs', false);
  4080. }
  4081. // Connection NAT State
  4082. const natStates = r.connection_nat_state || [];
  4083. if (natStates.length > 0) {
  4084. toggleMangleField('natstate', true);
  4085. ['srcnat', 'dstnat'].forEach(s => {
  4086. const el = document.getElementById(`mangle-modal-nat-${s}`);
  4087. if (el) el.checked = natStates.includes(s);
  4088. });
  4089. } else {
  4090. toggleMangleField('natstate', false);
  4091. }
  4092. // Advanced tab fields
  4093. setMangleFieldVal('layer7', r.layer7_protocol, false);
  4094. setMangleFieldVal('content', r.content, false);
  4095. setMangleFieldVal('connbytes', r.connection_bytes, false);
  4096. setMangleFieldVal('connrate', r.connection_rate, false);
  4097. setMangleFieldVal('pcc', r.pcc, false);
  4098. setMangleFieldVal('srcmac', r.src_mac_address, true);
  4099. setMangleFieldVal('outbridgeport', r.out_bridge_port, false);
  4100. setMangleFieldVal('inbridgeport', r.in_bridge_port, false);
  4101. setMangleFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  4102. setMangleFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  4103. setMangleFieldVal('ipsec', r.ipsec_policy, false);
  4104. setMangleFieldVal('tlshost', r.tls_host, false);
  4105. setMangleFieldVal('ingresspriority', r.ingress_priority, false);
  4106. setMangleFieldVal('priority', r.priority, false);
  4107. setMangleFieldVal('dscp', r.dscp, false);
  4108. setMangleFieldVal('tcpmss', r.tcp_mss, false);
  4109. if (r.tos) {
  4110. const tosEl = document.getElementById('mangle-val-tos');
  4111. if (tosEl) tosEl.value = r.tos;
  4112. }
  4113. setMangleFieldVal('pktsize', r.packet_size, false);
  4114. setMangleFieldVal('random', r.random, false);
  4115. setMangleFieldVal('tcpflags', r.tcp_flags, false);
  4116. setMangleFieldVal('icmpoptions', r.icmp_options, false);
  4117. setMangleFieldVal('ipv4options', r.ipv4_options, false);
  4118. setMangleFieldVal('ttl', r.ttl, false);
  4119. // Extra tab fields
  4120. setMangleFieldVal('nth', r.nth, false);
  4121. setMangleFieldVal('connlimit', r.connection_limit, false);
  4122. setMangleFieldVal('srcaddrtype', r.src_address_type, false);
  4123. setMangleFieldVal('dstaddrtype', r.dst_address_type, false);
  4124. setMangleFieldVal('hotspot', r.hotspot, false);
  4125. setMangleFieldVal('ipfragment', r.ip_fragment, false);
  4126. setMangleFieldVal('limit', r.limit, false);
  4127. setMangleFieldVal('dstlimit', r.dst_limit, false);
  4128. setMangleFieldVal('time', r.time, false);
  4129. setMangleFieldVal('psd', r.psd, false);
  4130. // Action fields
  4131. if (r.jump_target) {
  4132. const jtEl = document.getElementById('mangle-modal-jumptarget');
  4133. if (jtEl) jtEl.value = r.jump_target;
  4134. }
  4135. if (r.address_list) {
  4136. const alEl = document.getElementById('mangle-modal-action-addrlist');
  4137. if (alEl) alEl.value = r.address_list;
  4138. }
  4139. if (r.address_list_timeout) {
  4140. const toEl = document.getElementById('mangle-modal-action-timeout');
  4141. if (toEl) toEl.value = r.address_list_timeout;
  4142. }
  4143. setMangleFieldVal('logprefix', r.log_prefix, false);
  4144. // Statistics
  4145. const bEl = document.getElementById('mangle-stat-bytes');
  4146. const pEl = document.getElementById('mangle-stat-packets');
  4147. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  4148. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  4149. state.mangleLastBytes = r.bytes || 0;
  4150. state.mangleLastPackets = r.packets || 0;
  4151. state.mangleLastTimestamp = Date.now();
  4152. state.mangleStatRateHistory = new Array(30).fill(0);
  4153. state.mangleStatPktHistory = new Array(30).fill(0);
  4154. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4155. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4156. toggleMangleActionFields();
  4157. document.getElementById('mangle-modal').classList.remove('hidden');
  4158. }
  4159. function closeMangleModal() {
  4160. stopMangleStatPolling();
  4161. document.getElementById('mangle-modal').classList.add('hidden');
  4162. }
  4163. function copyMangleRule() {
  4164. document.getElementById('mangle-modal-id').value = '';
  4165. const badge = document.getElementById('mangle-modal-badge');
  4166. if (badge) badge.innerText = 'New...';
  4167. showToast('Rule Cloned', 'Ready to save as a new Mangle rule copy', 'info');
  4168. }
  4169. function resetCurrentMangleRuleCounters() {
  4170. state.mangleStatRateHistory = new Array(30).fill(0);
  4171. state.mangleStatPktHistory = new Array(30).fill(0);
  4172. state.mangleLastBytes = 0;
  4173. state.mangleLastPackets = 0;
  4174. state.mangleLastTimestamp = Date.now();
  4175. const bEl = document.getElementById('mangle-stat-bytes');
  4176. const pEl = document.getElementById('mangle-stat-packets');
  4177. const rEl = document.getElementById('mangle-stat-rate');
  4178. const prEl = document.getElementById('mangle-stat-pktrate');
  4179. if (bEl) bEl.value = '0 B';
  4180. if (pEl) pEl.value = '0';
  4181. if (rEl) rEl.value = '0 bps';
  4182. if (prEl) prEl.value = '0 p/s';
  4183. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4184. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4185. showToast('Counters Reset', 'Mangle rule counter display reset to 0', 'info');
  4186. }
  4187. async function applyMangleRule(closeAfter = false) {
  4188. const id = document.getElementById('mangle-modal-id').value;
  4189. const chain = document.getElementById('mangle-modal-chain').value;
  4190. const action = document.getElementById('mangle-modal-action').value;
  4191. const comment = document.getElementById('mangle-modal-comment').value.trim();
  4192. const enabled = document.getElementById('mangle-modal-enabled').checked;
  4193. const src = getMangleFieldVal('src', true);
  4194. const dst = getMangleFieldVal('dst', true);
  4195. const srclist = getMangleFieldVal('srclist', true);
  4196. const dstlist = getMangleFieldVal('dstlist', true);
  4197. const srcgeo = getMangleFieldVal('srcgeo', true);
  4198. const dstgeo = getMangleFieldVal('dstgeo', true);
  4199. const proto = getMangleFieldVal('proto', true);
  4200. const sport = getMangleFieldVal('sport', true);
  4201. const dport = getMangleFieldVal('dport', true);
  4202. const anyport = getMangleFieldVal('anyport', true);
  4203. const iniface = getMangleFieldVal('iniface', true);
  4204. const outiface = getMangleFieldVal('outiface', true);
  4205. const inifacelist = getMangleFieldVal('inifacelist', true);
  4206. const outifacelist = getMangleFieldVal('outifacelist', true);
  4207. const pktmark = getMangleFieldVal('pktmark', true);
  4208. const connmark = getMangleFieldVal('connmark', true);
  4209. const routingmark = getMangleFieldVal('routingmark', true);
  4210. const conntype = getMangleFieldVal('conntype', false);
  4211. const states = [];
  4212. const csBox = document.getElementById('mangle-field-cs');
  4213. if (csBox && !csBox.classList.contains('hidden')) {
  4214. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  4215. if (document.getElementById(`mangle-modal-cs-${s}`)?.checked) states.push(s);
  4216. });
  4217. }
  4218. const natStates = [];
  4219. const natBox = document.getElementById('mangle-field-natstate');
  4220. if (natBox && !natBox.classList.contains('hidden')) {
  4221. ['srcnat', 'dstnat'].forEach(s => {
  4222. if (document.getElementById(`mangle-modal-nat-${s}`)?.checked) natStates.push(s);
  4223. });
  4224. }
  4225. const payload = {
  4226. id,
  4227. chain,
  4228. action,
  4229. protocol: proto || 'all',
  4230. src_address: src,
  4231. dst_address: dst,
  4232. src_port: sport,
  4233. dst_port: dport,
  4234. any_port: anyport,
  4235. in_interface: iniface,
  4236. out_interface: outiface,
  4237. in_interface_list: inifacelist,
  4238. out_interface_list: outifacelist,
  4239. packet_mark: pktmark,
  4240. connection_mark: connmark,
  4241. routing_mark: routingmark,
  4242. connection_type: conntype,
  4243. connection_state: states,
  4244. connection_nat_state: natStates,
  4245. src_address_list: srclist,
  4246. dst_address_list: dstlist,
  4247. src_geoip: srcgeo,
  4248. dst_geoip: dstgeo,
  4249. comment,
  4250. disabled: !enabled,
  4251. // Advanced tab
  4252. layer7_protocol: getMangleFieldVal('layer7', false),
  4253. content: getMangleFieldVal('content', false),
  4254. connection_bytes: getMangleFieldVal('connbytes', false),
  4255. connection_rate: getMangleFieldVal('connrate', false),
  4256. pcc: getMangleFieldVal('pcc', false),
  4257. src_mac_address: getMangleFieldVal('srcmac', true),
  4258. out_bridge_port: getMangleFieldVal('outbridgeport', false),
  4259. in_bridge_port: getMangleFieldVal('inbridgeport', false),
  4260. in_bridge_port_list: getMangleFieldVal('inbridgeportlist', false),
  4261. out_bridge_port_list: getMangleFieldVal('outbridgeportlist', false),
  4262. ipsec_policy: getMangleFieldVal('ipsec', false),
  4263. tls_host: getMangleFieldVal('tlshost', false),
  4264. ingress_priority: getMangleFieldVal('ingresspriority', false),
  4265. priority: getMangleFieldVal('priority', false),
  4266. dscp: getMangleFieldVal('dscp', false),
  4267. tcp_mss: getMangleFieldVal('tcpmss', false),
  4268. tos: document.getElementById('mangle-val-tos')?.value || '',
  4269. packet_size: getMangleFieldVal('pktsize', false),
  4270. random: getMangleFieldVal('random', false),
  4271. tcp_flags: getMangleFieldVal('tcpflags', false),
  4272. icmp_options: getMangleFieldVal('icmpoptions', false),
  4273. ipv4_options: getMangleFieldVal('ipv4options', false),
  4274. ttl: getMangleFieldVal('ttl', false),
  4275. // Extra tab
  4276. nth: getMangleFieldVal('nth', false),
  4277. connection_limit: getMangleFieldVal('connlimit', false),
  4278. src_address_type: getMangleFieldVal('srcaddrtype', false),
  4279. dst_address_type: getMangleFieldVal('dstaddrtype', false),
  4280. hotspot: getMangleFieldVal('hotspot', false),
  4281. ip_fragment: getMangleFieldVal('ipfragment', false),
  4282. limit: getMangleFieldVal('limit', false),
  4283. dst_limit: getMangleFieldVal('dstlimit', false),
  4284. time: getMangleFieldVal('time', false),
  4285. psd: getMangleFieldVal('psd', false),
  4286. // Action tab
  4287. new_connection_mark: action === 'mark-connection' ? (document.getElementById('mangle-modal-newconnmark')?.value.trim() || '') : '',
  4288. new_routing_mark: action === 'mark-routing' ? (document.getElementById('mangle-modal-newroutingmark')?.value.trim() || '') : '',
  4289. new_packet_mark: action === 'mark-packet' ? (document.getElementById('mangle-modal-newpktmark')?.value.trim() || '') : '',
  4290. new_mss: action === 'change-mss' ? (document.getElementById('mangle-modal-newmss')?.value.trim() || '') : '',
  4291. new_dscp: action === 'change-dscp' ? parseInt(document.getElementById('mangle-modal-newdscp')?.value || '0', 10) : 0,
  4292. new_ttl: action === 'change-ttl' ? (document.getElementById('mangle-modal-newttl')?.value.trim() || '') : '',
  4293. new_priority: action === 'set-priority' ? (document.getElementById('mangle-modal-newpriority')?.value.trim() || '') : '',
  4294. route: action === 'route' ? (document.getElementById('mangle-modal-route')?.value.trim() || '') : '',
  4295. sniff_target: (action === 'sniff-pc' || action === 'sniff-tzsp') ? (document.getElementById('mangle-modal-sniff')?.value.trim() || '') : '',
  4296. passthrough: document.getElementById('mangle-modal-passthrough')?.checked ?? true,
  4297. jump_target: action === 'jump' ? (document.getElementById('mangle-modal-jumptarget')?.value || '') : '',
  4298. address_list: action.includes('address') ? (document.getElementById('mangle-modal-action-addrlist')?.value || '') : '',
  4299. address_list_timeout: action.includes('address') ? (document.getElementById('mangle-modal-action-timeout')?.value || '') : '',
  4300. log: document.getElementById('mangle-modal-log')?.checked || false,
  4301. log_prefix: getMangleFieldVal('logprefix', false)
  4302. };
  4303. try {
  4304. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  4305. method: 'POST',
  4306. headers: { 'Content-Type': 'application/json' },
  4307. body: JSON.stringify(payload)
  4308. });
  4309. if (res.ok) {
  4310. const data = await res.json();
  4311. showToast('Mangle Rule Saved', 'Marking rule updated', 'success');
  4312. loadFirewall(false);
  4313. if (closeAfter) {
  4314. closeMangleModal();
  4315. } else {
  4316. if (data.id) {
  4317. document.getElementById('mangle-modal-id').value = data.id;
  4318. const badge = document.getElementById('mangle-modal-badge');
  4319. if (badge) badge.innerText = `#${data.id}`;
  4320. }
  4321. }
  4322. } else {
  4323. const err = await res.json();
  4324. showToast('Error', err.message || 'Failed to save mangle rule', 'error');
  4325. }
  4326. } catch (err) {
  4327. showToast('Error', err.message, 'error');
  4328. }
  4329. }
  4330. function submitSaveMangleRule(e) {
  4331. if (e && e.preventDefault) e.preventDefault();
  4332. return applyMangleRule(true);
  4333. }
  4334. function startMangleStatPolling() {
  4335. stopMangleStatPolling();
  4336. pollMangleRuleStats();
  4337. state.mangleStatInterval = setInterval(pollMangleRuleStats, 1000);
  4338. }
  4339. function stopMangleStatPolling() {
  4340. if (state.mangleStatInterval) {
  4341. clearInterval(state.mangleStatInterval);
  4342. state.mangleStatInterval = null;
  4343. }
  4344. }
  4345. async function pollMangleRuleStats() {
  4346. const id = document.getElementById('mangle-modal-id')?.value;
  4347. if (!id) {
  4348. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory || new Array(30).fill(0), 'bps', 'mangle-stat-legend-rate');
  4349. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory || new Array(30).fill(0), 'p/s', 'mangle-stat-legend-pktrate');
  4350. return;
  4351. }
  4352. try {
  4353. const res = await fetch(`${API_BASE}/firewall/mangle`);
  4354. if (!res.ok) return;
  4355. const rules = await res.json();
  4356. const r = rules.find(x => x.id === id);
  4357. if (!r) return;
  4358. const now = Date.now();
  4359. const dt = Math.max(0.2, (now - (state.mangleLastTimestamp || now)) / 1000);
  4360. state.mangleLastTimestamp = now;
  4361. const curBytes = r.bytes || 0;
  4362. const curPackets = r.packets || 0;
  4363. const deltaBytes = Math.max(0, curBytes - (state.mangleLastBytes || curBytes));
  4364. const deltaPkts = Math.max(0, curPackets - (state.mangleLastPackets || curPackets));
  4365. state.mangleLastBytes = curBytes;
  4366. state.mangleLastPackets = curPackets;
  4367. const rateBps = Math.round((deltaBytes * 8) / dt);
  4368. const ratePkt = Math.round(deltaPkts / dt);
  4369. if (!state.mangleStatRateHistory) state.mangleStatRateHistory = new Array(30).fill(0);
  4370. if (!state.mangleStatPktHistory) state.mangleStatPktHistory = new Array(30).fill(0);
  4371. state.mangleStatRateHistory.push(rateBps);
  4372. if (state.mangleStatRateHistory.length > 30) state.mangleStatRateHistory.shift();
  4373. state.mangleStatPktHistory.push(ratePkt);
  4374. if (state.mangleStatPktHistory.length > 30) state.mangleStatPktHistory.shift();
  4375. const bEl = document.getElementById('mangle-stat-bytes');
  4376. const pEl = document.getElementById('mangle-stat-packets');
  4377. const rEl = document.getElementById('mangle-stat-rate');
  4378. const prEl = document.getElementById('mangle-stat-pktrate');
  4379. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4380. if (pEl) pEl.value = curPackets.toLocaleString();
  4381. if (rEl) rEl.value = formatBps(rateBps);
  4382. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4383. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4384. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4385. } catch (e) {
  4386. console.error('Error polling Mangle rule stats', e);
  4387. }
  4388. }
  4389. async function moveMangleRule(id, dir) {
  4390. try {
  4391. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  4392. method: 'POST',
  4393. headers: { 'Content-Type': 'application/json' },
  4394. body: JSON.stringify({ direction: dir })
  4395. });
  4396. if (res.ok) loadFirewall(false);
  4397. } catch (err) {
  4398. showToast('Error', err.message, 'error');
  4399. }
  4400. }
  4401. async function toggleMangleRuleState(id, disabled) {
  4402. try {
  4403. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  4404. method: 'POST',
  4405. headers: { 'Content-Type': 'application/json' },
  4406. body: JSON.stringify({ disabled })
  4407. });
  4408. if (res.ok) loadFirewall(false);
  4409. } catch (err) {
  4410. showToast('Error', err.message, 'error');
  4411. }
  4412. }
  4413. async function deleteMangleRule(id) {
  4414. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  4415. try {
  4416. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4417. if (res.ok) {
  4418. showToast('Deleted', 'Mangle rule removed', 'success');
  4419. loadFirewall(false);
  4420. }
  4421. } catch (err) {
  4422. showToast('Error', err.message, 'error');
  4423. }
  4424. }
  4425. // ----------------- Address Lists -----------------
  4426. function renderAddressLists() {
  4427. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  4428. const tbody = document.getElementById('addrlist-table-body');
  4429. const empty = document.getElementById('addrlist-empty');
  4430. if (!tbody) return;
  4431. tbody.innerHTML = '';
  4432. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  4433. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries`;
  4434. // Update filter select
  4435. const sel = document.getElementById('addrlist-filter-name');
  4436. if (sel) {
  4437. const cur = sel.value;
  4438. sel.innerHTML = '<option value="">All Lists</option>';
  4439. const set = new Set((state.addressLists || []).map(a => a.name));
  4440. set.forEach(n => {
  4441. const opt = document.createElement('option');
  4442. opt.value = n;
  4443. opt.innerText = n;
  4444. if (n === cur) opt.selected = true;
  4445. sel.appendChild(opt);
  4446. });
  4447. }
  4448. if (entries.length === 0) {
  4449. empty?.classList.remove('hidden');
  4450. return;
  4451. }
  4452. empty?.classList.add('hidden');
  4453. entries.forEach((e, idx) => {
  4454. const tr = document.createElement('tr');
  4455. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
  4456. tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
  4457. tr.innerHTML = `
  4458. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  4459. <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>
  4460. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  4461. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  4462. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]">${e.comment || '-'}</td>
  4463. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  4464. <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>
  4465. <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
  4466. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4467. </td>
  4468. `;
  4469. tbody.appendChild(tr);
  4470. });
  4471. populateCommonAddrListDatalist();
  4472. }
  4473. function openAddAddrListModal() {
  4474. document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
  4475. document.getElementById('addrlist-modal-id').value = '';
  4476. document.getElementById('addrlist-modal-name').value = '';
  4477. document.getElementById('addrlist-modal-addr').value = '';
  4478. document.getElementById('addrlist-modal-comment').value = '';
  4479. document.getElementById('addrlist-modal-disabled').checked = false;
  4480. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  4481. if (submitBtn) submitBtn.innerText = 'Add to List';
  4482. document.getElementById('addrlist-modal').classList.remove('hidden');
  4483. }
  4484. function openEditAddrListModal(id) {
  4485. const e = (state.addressLists || []).find(item => item.id === id);
  4486. if (!e) return;
  4487. document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
  4488. document.getElementById('addrlist-modal-id').value = e.id;
  4489. document.getElementById('addrlist-modal-name').value = e.name;
  4490. document.getElementById('addrlist-modal-addr').value = e.address;
  4491. document.getElementById('addrlist-modal-comment').value = e.comment || '';
  4492. document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
  4493. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  4494. if (submitBtn) submitBtn.innerText = 'Save Changes';
  4495. document.getElementById('addrlist-modal').classList.remove('hidden');
  4496. }
  4497. function closeAddrListModal() {
  4498. document.getElementById('addrlist-modal').classList.add('hidden');
  4499. }
  4500. async function submitSaveAddrList(e) {
  4501. e.preventDefault();
  4502. const id = document.getElementById('addrlist-modal-id').value;
  4503. const name = document.getElementById('addrlist-modal-name').value.trim();
  4504. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  4505. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  4506. const disabled = document.getElementById('addrlist-modal-disabled').checked;
  4507. try {
  4508. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  4509. method: 'POST',
  4510. headers: { 'Content-Type': 'application/json' },
  4511. body: JSON.stringify({ id, name, address: addr, comment, disabled })
  4512. });
  4513. if (res.ok) {
  4514. showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
  4515. closeAddrListModal();
  4516. loadFirewall(false);
  4517. } else {
  4518. const err = await res.json();
  4519. showToast('Error', err.message || 'Failed to save address list', 'error');
  4520. }
  4521. } catch (err) {
  4522. showToast('Error', err.message, 'error');
  4523. }
  4524. }
  4525. async function toggleAddrListState(id, disabled) {
  4526. try {
  4527. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
  4528. method: 'POST',
  4529. headers: { 'Content-Type': 'application/json' },
  4530. body: JSON.stringify({ disabled })
  4531. });
  4532. if (res.ok) {
  4533. loadFirewall(false);
  4534. }
  4535. } catch (err) {
  4536. showToast('Error', err.message, 'error');
  4537. }
  4538. }
  4539. async function deleteAddrList(id) {
  4540. if (!confirm('Are you sure you want to delete this address list item?')) return;
  4541. try {
  4542. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4543. if (res.ok) {
  4544. showToast('Deleted', 'Address list item removed', 'info');
  4545. loadFirewall(false);
  4546. }
  4547. } catch (err) {
  4548. showToast('Error', err.message, 'error');
  4549. }
  4550. }
  4551. // ----------------- Geo-Location IP Management -----------------
  4552. async function loadGeoIP() {
  4553. try {
  4554. const [statusRes, countriesRes] = await Promise.all([
  4555. fetch(`${API_BASE}/firewall/geoip/status`),
  4556. fetch(`${API_BASE}/firewall/geoip/countries`)
  4557. ]);
  4558. if (statusRes.ok) state.geoStatus = await statusRes.json();
  4559. if (countriesRes.ok) state.geoCountries = await countriesRes.json();
  4560. updateGeoHeader();
  4561. renderGeoCountries();
  4562. } catch (err) {
  4563. console.error('Failed to load GeoIP:', err);
  4564. }
  4565. }
  4566. function getGeoUsageMap() {
  4567. const usage = {};
  4568. const checkRule = (r, type) => {
  4569. ['src_geoip', 'dst_geoip'].forEach(field => {
  4570. let val = (r && r[field]) || '';
  4571. let code = val.replace(/^!/, '').replace(/^geo:/, '').replace(/^geo_/, '').toUpperCase().trim();
  4572. if (code) {
  4573. if (!usage[code]) usage[code] = [];
  4574. const label = `${type} #${r.priority !== undefined ? r.priority : (r.id || '')}`;
  4575. if (!usage[code].includes(label)) usage[code].push(label);
  4576. }
  4577. });
  4578. };
  4579. (state.filterRules || []).forEach(r => checkRule(r, 'Filter'));
  4580. (state.natRules || []).forEach(r => checkRule(r, 'NAT'));
  4581. (state.mangleRules || []).forEach(r => checkRule(r, 'Mangle'));
  4582. return usage;
  4583. }
  4584. function updateGeoHeader() {
  4585. const s = state.geoStatus || {};
  4586. const statusBadge = document.getElementById('geo-status-badge');
  4587. if (statusBadge) {
  4588. statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
  4589. statusBadge.className = s.auto_update
  4590. ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
  4591. : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
  4592. }
  4593. const intervalLabel = document.getElementById('geo-interval-label');
  4594. if (intervalLabel) {
  4595. intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
  4596. }
  4597. const usageMap = getGeoUsageMap();
  4598. const inUseCount = Object.keys(usageMap).length;
  4599. const activeCountEl = document.getElementById('geo-stat-active-countries');
  4600. if (activeCountEl) activeCountEl.innerText = inUseCount.toLocaleString();
  4601. const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
  4602. if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
  4603. const lastSyncEl = document.getElementById('geo-stat-last-sync');
  4604. if (lastSyncEl) {
  4605. if (s.last_updated && !s.last_updated.startsWith('0001')) {
  4606. const d = new Date(s.last_updated);
  4607. lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  4608. } else {
  4609. lastSyncEl.innerText = 'Never (Sync Pending)';
  4610. }
  4611. }
  4612. const nextSyncEl = document.getElementById('geo-stat-next-sync');
  4613. if (nextSyncEl) {
  4614. if (s.next_update && !s.next_update.startsWith('0001')) {
  4615. const d = new Date(s.next_update);
  4616. nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  4617. } else {
  4618. nextSyncEl.innerText = '-';
  4619. }
  4620. }
  4621. const badge = document.getElementById('fw-badge-geo');
  4622. if (badge) badge.innerText = inUseCount || (state.geoCountries || []).filter(c => c.subnet_count > 0).length || 0;
  4623. }
  4624. function renderGeoCountries() {
  4625. const tbody = document.getElementById('geo-table-body');
  4626. const empty = document.getElementById('geo-empty');
  4627. if (!tbody) return;
  4628. tbody.innerHTML = '';
  4629. const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
  4630. const continent = document.getElementById('geo-continent-filter')?.value || '';
  4631. const inUseOnly = document.getElementById('geo-filter-inuse-only')?.checked;
  4632. const cachedOnly = document.getElementById('geo-filter-cached-only')?.checked;
  4633. const usageMap = getGeoUsageMap();
  4634. const countries = (state.geoCountries || []).filter(c => {
  4635. const isUsed = !!usageMap[c.code];
  4636. if (inUseOnly && !isUsed) return false;
  4637. if (cachedOnly && (!c.subnet_count || c.subnet_count === 0)) return false;
  4638. if (continent && c.continent !== continent) return false;
  4639. if (q) {
  4640. const matchCode = c.code.toLowerCase().includes(q);
  4641. const matchName = c.name.toLowerCase().includes(q);
  4642. if (!matchCode && !matchName) return false;
  4643. }
  4644. return true;
  4645. });
  4646. if (countries.length === 0) {
  4647. empty?.classList.remove('hidden');
  4648. return;
  4649. }
  4650. empty?.classList.add('hidden');
  4651. countries.forEach(c => {
  4652. const tr = document.createElement('tr');
  4653. const isUsed = !!usageMap[c.code];
  4654. const rulesUsing = usageMap[c.code] || [];
  4655. tr.className = `hover:bg-slate-800/40 transition text-xs ${isUsed ? 'bg-emerald-950/20' : ''}`;
  4656. let statusHtml = '';
  4657. if (isUsed) {
  4658. 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>`;
  4659. } else if (c.subnet_count > 0) {
  4660. 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>';
  4661. } else {
  4662. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-slate-500 bg-slate-800/60">READY</span>';
  4663. }
  4664. tr.innerHTML = `
  4665. <td class="py-2.5 px-3 text-center">
  4666. <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'}">
  4667. ${c.code}
  4668. </span>
  4669. </td>
  4670. <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
  4671. <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
  4672. <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
  4673. ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
  4674. </td>
  4675. <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
  4676. <td class="py-2.5 px-3">
  4677. ${statusHtml}
  4678. </td>
  4679. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  4680. <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>
  4681. <button onclick="viewGeoSubnets('${c.code}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
  4682. </td>
  4683. `;
  4684. tbody.appendChild(tr);
  4685. });
  4686. }
  4687. function quickFilterGeo(preset) {
  4688. const searchInput = document.getElementById('geo-search-input');
  4689. const continentSel = document.getElementById('geo-continent-filter');
  4690. const inUseCheck = document.getElementById('geo-filter-inuse-only');
  4691. const cachedCheck = document.getElementById('geo-filter-cached-only');
  4692. if (searchInput) searchInput.value = '';
  4693. if (continentSel) continentSel.value = '';
  4694. if (inUseCheck) inUseCheck.checked = false;
  4695. if (cachedCheck) cachedCheck.checked = false;
  4696. if (preset === 'GR') {
  4697. if (searchInput) searchInput.value = 'Greece';
  4698. } else if (preset === 'Europe') {
  4699. if (continentSel) continentSel.value = 'Europe';
  4700. } else if (preset === 'HIGHRISK') {
  4701. if (searchInput) searchInput.value = 'China';
  4702. }
  4703. renderGeoCountries();
  4704. }
  4705. async function toggleGeoCountry(code, enabled) {
  4706. try {
  4707. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
  4708. method: 'POST',
  4709. headers: { 'Content-Type': 'application/json' },
  4710. body: JSON.stringify({ enabled })
  4711. });
  4712. if (res.ok) {
  4713. showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
  4714. loadGeoIP();
  4715. } else {
  4716. const err = await res.json();
  4717. showToast('Error', err.message || 'Failed to toggle country', 'error');
  4718. }
  4719. } catch (err) {
  4720. showToast('Error', err.message, 'error');
  4721. }
  4722. }
  4723. async function updateGeoCountry(code) {
  4724. try {
  4725. showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
  4726. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
  4727. if (res.ok) {
  4728. const data = await res.json();
  4729. showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
  4730. loadGeoIP();
  4731. } else {
  4732. const err = await res.json();
  4733. showToast('Sync Error', err.message || 'Failed to sync country', 'error');
  4734. }
  4735. } catch (err) {
  4736. showToast('Error', err.message, 'error');
  4737. }
  4738. }
  4739. async function triggerGeoUpdateNow() {
  4740. const spinner = document.getElementById('geo-update-spinner');
  4741. if (spinner) spinner.classList.remove('hidden');
  4742. try {
  4743. const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
  4744. if (res.ok) {
  4745. showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
  4746. setTimeout(() => {
  4747. loadGeoIP();
  4748. if (spinner) spinner.classList.add('hidden');
  4749. }, 2500);
  4750. } else {
  4751. const err = await res.json();
  4752. showToast('Notice', err.message || 'Update in progress', 'info');
  4753. if (spinner) spinner.classList.add('hidden');
  4754. }
  4755. } catch (err) {
  4756. showToast('Error', err.message, 'error');
  4757. if (spinner) spinner.classList.add('hidden');
  4758. }
  4759. }
  4760. async function applyGeoPreset(preset) {
  4761. try {
  4762. const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
  4763. method: 'POST',
  4764. headers: { 'Content-Type': 'application/json' },
  4765. body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
  4766. });
  4767. if (res.ok) {
  4768. showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
  4769. loadGeoIP();
  4770. }
  4771. } catch (err) {
  4772. showToast('Error', err.message, 'error');
  4773. }
  4774. }
  4775. function openGeoIntervalModal() {
  4776. const s = state.geoStatus || {};
  4777. document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
  4778. const sel = document.getElementById('geo-cfg-interval');
  4779. const customBox = document.getElementById('geo-cfg-custom-box');
  4780. const customHoursInput = document.getElementById('geo-cfg-custom-hours');
  4781. const curHours = s.interval_hours || 24;
  4782. const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
  4783. if (matchOption) {
  4784. sel.value = String(curHours);
  4785. customBox.classList.add('hidden');
  4786. } else {
  4787. sel.value = 'custom';
  4788. customHoursInput.value = curHours;
  4789. customBox.classList.remove('hidden');
  4790. }
  4791. document.getElementById('geo-interval-modal').classList.remove('hidden');
  4792. }
  4793. function closeGeoIntervalModal() {
  4794. document.getElementById('geo-interval-modal').classList.add('hidden');
  4795. }
  4796. function toggleCustomGeoInterval() {
  4797. const val = document.getElementById('geo-cfg-interval').value;
  4798. const customBox = document.getElementById('geo-cfg-custom-box');
  4799. if (val === 'custom') {
  4800. customBox.classList.remove('hidden');
  4801. } else {
  4802. customBox.classList.add('hidden');
  4803. }
  4804. }
  4805. async function submitGeoIntervalSettings(e) {
  4806. e.preventDefault();
  4807. const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
  4808. const intervalVal = document.getElementById('geo-cfg-interval').value;
  4809. let hours = 24;
  4810. if (intervalVal === 'custom') {
  4811. hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
  4812. } else {
  4813. hours = parseInt(intervalVal, 10) || 24;
  4814. }
  4815. try {
  4816. const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
  4817. method: 'POST',
  4818. headers: { 'Content-Type': 'application/json' },
  4819. body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
  4820. });
  4821. if (res.ok) {
  4822. showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
  4823. closeGeoIntervalModal();
  4824. loadGeoIP();
  4825. } else {
  4826. const err = await res.json();
  4827. showToast('Error', err.message || 'Failed to save schedule', 'error');
  4828. }
  4829. } catch (err) {
  4830. showToast('Error', err.message, 'error');
  4831. }
  4832. }
  4833. async function viewGeoSubnets(code, name) {
  4834. if (!name) {
  4835. const found = (state.geoCountries || []).find(x => x.code === code);
  4836. name = found ? found.name : code;
  4837. }
  4838. document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
  4839. document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
  4840. const listEl = document.getElementById('geo-subnets-list');
  4841. listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
  4842. document.getElementById('geo-subnets-modal').classList.remove('hidden');
  4843. try {
  4844. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
  4845. if (res.ok) {
  4846. const data = await res.json();
  4847. const subnets = data.subnets || [];
  4848. if (subnets.length === 0) {
  4849. listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
  4850. } else {
  4851. listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
  4852. }
  4853. } else {
  4854. listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
  4855. }
  4856. } catch (err) {
  4857. listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
  4858. }
  4859. }
  4860. function closeGeoSubnetsModal() {
  4861. document.getElementById('geo-subnets-modal').classList.add('hidden');
  4862. }
  4863. // ----------------- Active Connections Tracking -----------------
  4864. async function loadConnections() {
  4865. try {
  4866. const res = await fetch(`${API_BASE}/firewall/connections`);
  4867. const data = await res.json();
  4868. state.connections = Array.isArray(data) ? data : [];
  4869. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  4870. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  4871. renderConnections();
  4872. } catch (err) {
  4873. console.error('Failed to load connections:', err);
  4874. }
  4875. }
  4876. function renderConnections() {
  4877. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  4878. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  4879. const tbody = document.getElementById('conns-table-body');
  4880. const empty = document.getElementById('conns-empty');
  4881. if (!tbody) return;
  4882. tbody.innerHTML = '';
  4883. const conns = (state.connections || []).filter(c => {
  4884. if (protoFilter && c.protocol !== protoFilter) return false;
  4885. if (search) {
  4886. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  4887. if (!line.includes(search)) return false;
  4888. }
  4889. return true;
  4890. });
  4891. if (conns.length === 0) {
  4892. empty?.classList.remove('hidden');
  4893. return;
  4894. }
  4895. empty?.classList.add('hidden');
  4896. conns.slice(0, 150).forEach(c => {
  4897. const tr = document.createElement('tr');
  4898. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  4899. let stateColor = 'text-slate-400';
  4900. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  4901. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  4902. tr.innerHTML = `
  4903. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  4904. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  4905. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  4906. <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>
  4907. <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>
  4908. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  4909. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  4910. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  4911. <td class="py-2.5 px-3 text-right font-sans">
  4912. <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>
  4913. </td>
  4914. `;
  4915. tbody.appendChild(tr);
  4916. });
  4917. }
  4918. async function killConnection(protocol, src, sport, dst, dport) {
  4919. try {
  4920. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  4921. method: 'POST',
  4922. headers: { 'Content-Type': 'application/json' },
  4923. body: JSON.stringify({ protocol, src, sport, dst, dport })
  4924. });
  4925. if (res.ok) {
  4926. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  4927. loadConnections();
  4928. }
  4929. } catch (err) {
  4930. showToast('Error', err.message, 'error');
  4931. }
  4932. }
  4933. async function resetFirewallCounters() {
  4934. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  4935. try {
  4936. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  4937. if (res.ok) {
  4938. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  4939. loadFirewall(false);
  4940. }
  4941. } catch (err) {
  4942. showToast('Error', err.message, 'error');
  4943. }
  4944. }
  4945. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  4946. function switchRoutesSubTab(tab) {
  4947. state.routesSubTab = tab;
  4948. const tabs = ['routes', 'rules', 'tables'];
  4949. tabs.forEach(t => {
  4950. const panel = document.getElementById(`routes-subtab-${t}`);
  4951. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  4952. if (panel) {
  4953. if (t === tab) panel.classList.remove('hidden');
  4954. else panel.classList.add('hidden');
  4955. }
  4956. if (btn) {
  4957. if (t === tab) {
  4958. 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';
  4959. } else {
  4960. 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';
  4961. }
  4962. }
  4963. });
  4964. setTimeout(initTableSorting, 50);
  4965. }
  4966. async function loadRoutes() {
  4967. try {
  4968. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  4969. fetch(`${API_BASE}/routes`),
  4970. fetch(`${API_BASE}/routing/rules`),
  4971. fetch(`${API_BASE}/routing/tables`)
  4972. ]);
  4973. if (routesRes.ok) state.routes = await routesRes.json();
  4974. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  4975. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  4976. const bRoutes = document.getElementById('routes-badge-routes');
  4977. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  4978. const showSystem = document.getElementById('prule-show-system')?.checked;
  4979. const userRules = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  4980. const bRules = document.getElementById('routes-badge-rules');
  4981. if (bRules) bRules.innerText = userRules.length;
  4982. const bTables = document.getElementById('routes-badge-tables');
  4983. if (bTables) bTables.innerText = (state.routingTables || []).length;
  4984. const bRoutesCount = document.getElementById('badge-routes-count');
  4985. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  4986. renderRoutesList();
  4987. renderPolicyRules();
  4988. renderRoutingTables();
  4989. } catch (err) {
  4990. console.error('Failed to load routing:', err);
  4991. }
  4992. }
  4993. function renderRoutesList() {
  4994. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  4995. const tbody = document.getElementById('routes-table-body');
  4996. const empty = document.getElementById('routes-empty');
  4997. if (!tbody) return;
  4998. tbody.innerHTML = '';
  4999. // Update table filter select
  5000. const sel = document.getElementById('routes-filter-table');
  5001. if (sel) {
  5002. const cur = sel.value;
  5003. sel.innerHTML = '<option value="">All Tables</option>';
  5004. (state.routingTables || []).forEach(t => {
  5005. const opt = document.createElement('option');
  5006. opt.value = t.name;
  5007. opt.innerText = t.name;
  5008. if (t.name === cur) opt.selected = true;
  5009. sel.appendChild(opt);
  5010. });
  5011. }
  5012. const routes = (state.routes || []).filter(r => !tableFilter || r.routing_table === tableFilter);
  5013. document.getElementById('routes-count-badge').innerText = `${routes.length} Routes`;
  5014. if (routes.length === 0) {
  5015. empty?.classList.remove('hidden');
  5016. return;
  5017. }
  5018. empty?.classList.add('hidden');
  5019. routes.forEach(r => {
  5020. const tr = document.createElement('tr');
  5021. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  5022. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  5023. // MikroTik Flags string: D=Dynamic, A=Active, C=Connect, S=Static, X=Disabled
  5024. let flags = '';
  5025. if (r.dynamic) flags += 'D';
  5026. if (r.active) flags += 'A';
  5027. if (r.connect) flags += 'C';
  5028. if (r.static) flags += 'S';
  5029. if (r.disabled) flags += 'X';
  5030. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  5031. tr.innerHTML = `
  5032. <td class="py-2.5 px-3 text-center">
  5033. <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'}">
  5034. ${flags || '-'}
  5035. </span>
  5036. </td>
  5037. <td class="py-2.5 px-3 font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${r.dst_address}</td>
  5038. <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>
  5039. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  5040. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  5041. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  5042. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  5043. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5044. ${r.static ? `
  5045. <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>
  5046. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  5047. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5048. ` : `
  5049. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  5050. `}
  5051. </td>
  5052. `;
  5053. tbody.appendChild(tr);
  5054. });
  5055. }
  5056. function openAddRouteModal() {
  5057. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  5058. document.getElementById('route-modal-id').value = '';
  5059. document.getElementById('route-modal-old-dst').value = '';
  5060. document.getElementById('route-modal-old-gw').value = '';
  5061. document.getElementById('route-modal-old-distance').value = '';
  5062. document.getElementById('route-modal-old-table').value = '';
  5063. document.getElementById('route-modal-old-iface').value = '';
  5064. const dstInput = document.getElementById('route-modal-dst');
  5065. const gwInput = document.getElementById('route-modal-gw');
  5066. const distInput = document.getElementById('route-modal-distance');
  5067. const ifaceSelect = document.getElementById('route-modal-iface');
  5068. const tableSelect = document.getElementById('route-modal-table');
  5069. const commentInput = document.getElementById('route-modal-comment');
  5070. const disCheck = document.getElementById('route-modal-disabled');
  5071. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  5072. dstInput.disabled = false;
  5073. dstInput.value = '0.0.0.0/0';
  5074. gwInput.disabled = false;
  5075. gwInput.value = '';
  5076. distInput.disabled = false;
  5077. distInput.value = '1';
  5078. ifaceSelect.disabled = false;
  5079. tableSelect.disabled = false;
  5080. commentInput.disabled = false;
  5081. commentInput.value = '';
  5082. disCheck.disabled = false;
  5083. disCheck.checked = false;
  5084. if (saveBtn) saveBtn.classList.remove('hidden');
  5085. populateInterfaceSelect('route-modal-iface');
  5086. // Populate tables
  5087. tableSelect.innerHTML = '';
  5088. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  5089. const opt = document.createElement('option');
  5090. opt.value = t.name;
  5091. opt.innerText = t.name;
  5092. if (t.name === 'main') opt.selected = true;
  5093. tableSelect.appendChild(opt);
  5094. });
  5095. document.getElementById('route-modal').classList.remove('hidden');
  5096. }
  5097. function openEditRouteModal(id) {
  5098. const r = (state.routes || []).find(route => route.id === id);
  5099. if (!r) return;
  5100. const isStatic = !!r.static;
  5101. document.getElementById('route-modal-title').innerText = isStatic
  5102. ? `Edit Route: ${r.dst_address}`
  5103. : `Route Properties (Read Only): ${r.dst_address}`;
  5104. document.getElementById('route-modal-id').value = r.id;
  5105. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  5106. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  5107. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  5108. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  5109. document.getElementById('route-modal-old-iface').value = r.interface || '';
  5110. const dstInput = document.getElementById('route-modal-dst');
  5111. const gwInput = document.getElementById('route-modal-gw');
  5112. const distInput = document.getElementById('route-modal-distance');
  5113. const ifaceSelect = document.getElementById('route-modal-iface');
  5114. const tableSelect = document.getElementById('route-modal-table');
  5115. const commentInput = document.getElementById('route-modal-comment');
  5116. const disCheck = document.getElementById('route-modal-disabled');
  5117. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  5118. dstInput.value = r.dst_address;
  5119. gwInput.value = r.gateway || '';
  5120. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  5121. commentInput.value = r.comment || '';
  5122. disCheck.checked = !!r.disabled;
  5123. dstInput.disabled = !isStatic;
  5124. gwInput.disabled = !isStatic;
  5125. distInput.disabled = !isStatic;
  5126. ifaceSelect.disabled = !isStatic;
  5127. tableSelect.disabled = !isStatic;
  5128. commentInput.disabled = !isStatic;
  5129. disCheck.disabled = !isStatic;
  5130. if (saveBtn) {
  5131. if (isStatic) {
  5132. saveBtn.classList.remove('hidden');
  5133. } else {
  5134. saveBtn.classList.add('hidden');
  5135. }
  5136. }
  5137. populateInterfaceSelect('route-modal-iface', r.interface);
  5138. tableSelect.innerHTML = '';
  5139. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  5140. const opt = document.createElement('option');
  5141. opt.value = t.name;
  5142. opt.innerText = t.name;
  5143. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  5144. tableSelect.appendChild(opt);
  5145. });
  5146. document.getElementById('route-modal').classList.remove('hidden');
  5147. }
  5148. function closeRouteModal() {
  5149. document.getElementById('route-modal').classList.add('hidden');
  5150. }
  5151. async function submitSaveRoute(e) {
  5152. e.preventDefault();
  5153. const id = document.getElementById('route-modal-id').value;
  5154. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  5155. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  5156. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  5157. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  5158. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  5159. const dst = document.getElementById('route-modal-dst').value.trim();
  5160. const gw = document.getElementById('route-modal-gw').value.trim();
  5161. const table = document.getElementById('route-modal-table').value;
  5162. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  5163. const iface = document.getElementById('route-modal-iface').value;
  5164. const comment = document.getElementById('route-modal-comment').value.trim();
  5165. const disabled = document.getElementById('route-modal-disabled').checked;
  5166. if (!dst) {
  5167. showToast('Error', 'Destination address is required', 'error');
  5168. return;
  5169. }
  5170. if (!gw && !iface) {
  5171. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  5172. return;
  5173. }
  5174. const payload = {
  5175. id,
  5176. old_dst_address: oldDst,
  5177. old_gateway: oldGw,
  5178. old_routing_table: oldTable,
  5179. old_interface: oldIface,
  5180. dst_address: dst,
  5181. gateway: gw || iface,
  5182. routing_table: table,
  5183. distance,
  5184. interface: iface,
  5185. comment,
  5186. disabled
  5187. };
  5188. if (oldDistStr !== undefined && oldDistStr !== '') {
  5189. payload.old_distance = parseInt(oldDistStr, 10);
  5190. }
  5191. try {
  5192. const res = await fetch(`${API_BASE}/routes`, {
  5193. method: 'POST',
  5194. headers: { 'Content-Type': 'application/json' },
  5195. body: JSON.stringify(payload)
  5196. });
  5197. if (res.ok) {
  5198. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  5199. closeRouteModal();
  5200. loadRoutes();
  5201. } else {
  5202. const err = await res.json();
  5203. showToast('Error', err.message || 'Failed to save route', 'error');
  5204. }
  5205. } catch (err) {
  5206. showToast('Error', err.message, 'error');
  5207. }
  5208. }
  5209. async function toggleRouteState(id, disabled) {
  5210. try {
  5211. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  5212. method: 'POST',
  5213. headers: { 'Content-Type': 'application/json' },
  5214. body: JSON.stringify({ disabled })
  5215. });
  5216. if (res.ok) loadRoutes();
  5217. } catch (err) {
  5218. showToast('Error', err.message, 'error');
  5219. }
  5220. }
  5221. async function deleteRoute(id) {
  5222. if (!confirm('Are you sure you want to delete this route?')) return;
  5223. try {
  5224. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5225. if (res.ok) {
  5226. showToast('Deleted', 'Route removed', 'success');
  5227. loadRoutes();
  5228. }
  5229. } catch (err) {
  5230. showToast('Error', err.message, 'error');
  5231. }
  5232. }
  5233. // ----------------- Policy Rules (/ip route rule) -----------------
  5234. function renderPolicyRules() {
  5235. const tbody = document.getElementById('rules-table-body');
  5236. const empty = document.getElementById('rules-empty');
  5237. if (!tbody) return;
  5238. tbody.innerHTML = '';
  5239. const showSystem = document.getElementById('prule-show-system')?.checked;
  5240. const filtered = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  5241. const countBadge = document.getElementById('rules-count-badge');
  5242. if (countBadge) countBadge.innerText = `${filtered.length} Rules`;
  5243. const bRules = document.getElementById('routes-badge-rules');
  5244. if (bRules) bRules.innerText = filtered.length;
  5245. if (filtered.length === 0) {
  5246. empty?.classList.remove('hidden');
  5247. return;
  5248. }
  5249. empty?.classList.add('hidden');
  5250. filtered.forEach(pr => {
  5251. const isSys = pr.is_default || pr.is_system;
  5252. const tr = document.createElement('tr');
  5253. tr.className = `hover:bg-slate-800/40 transition text-xs ${isSys ? 'opacity-70 bg-slate-950/20' : ''}`;
  5254. tr.innerHTML = `
  5255. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  5256. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  5257. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  5258. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  5259. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  5260. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  5261. <td class="py-2.5 px-3 text-right font-sans">
  5262. ${!pr.is_default ? `
  5263. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5264. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  5265. </td>
  5266. `;
  5267. tbody.appendChild(tr);
  5268. });
  5269. }
  5270. function openAddPolicyRuleModal() {
  5271. const userRules = (state.policyRules || []).filter(pr => !pr.is_default && !pr.is_system);
  5272. document.getElementById('prule-modal-pref').value = userRules.length * 10 + 1000;
  5273. document.getElementById('prule-modal-mark').value = '';
  5274. document.getElementById('prule-modal-src').value = '';
  5275. document.getElementById('prule-modal-dst').value = '';
  5276. const sel = document.getElementById('prule-modal-table');
  5277. sel.innerHTML = '';
  5278. (state.routingTables || []).forEach(t => {
  5279. const opt = document.createElement('option');
  5280. opt.value = t.name;
  5281. opt.innerText = t.name;
  5282. sel.appendChild(opt);
  5283. });
  5284. document.getElementById('prule-modal').classList.remove('hidden');
  5285. }
  5286. function closePolicyRuleModal() {
  5287. document.getElementById('prule-modal').classList.add('hidden');
  5288. }
  5289. async function submitSavePolicyRule(e) {
  5290. e.preventDefault();
  5291. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  5292. const mark = document.getElementById('prule-modal-mark').value.trim();
  5293. const src = document.getElementById('prule-modal-src').value.trim();
  5294. const dst = document.getElementById('prule-modal-dst').value.trim();
  5295. const table = document.getElementById('prule-modal-table').value;
  5296. const action = document.getElementById('prule-modal-action').value;
  5297. try {
  5298. const res = await fetch(`${API_BASE}/routing/rules`, {
  5299. method: 'POST',
  5300. headers: { 'Content-Type': 'application/json' },
  5301. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  5302. });
  5303. if (res.ok) {
  5304. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  5305. closePolicyRuleModal();
  5306. loadRoutes();
  5307. } else {
  5308. const err = await res.json();
  5309. showToast('Error', err.message, 'error');
  5310. }
  5311. } catch (err) {
  5312. showToast('Error', err.message, 'error');
  5313. }
  5314. }
  5315. async function deletePolicyRule(id) {
  5316. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  5317. try {
  5318. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5319. if (res.ok) {
  5320. showToast('Rule Removed', 'Policy rule deleted', 'success');
  5321. loadRoutes();
  5322. }
  5323. } catch (err) {
  5324. showToast('Error', err.message, 'error');
  5325. }
  5326. }
  5327. // ----------------- Routing Tables -----------------
  5328. function renderRoutingTables() {
  5329. const tbody = document.getElementById('tables-table-body');
  5330. if (!tbody) return;
  5331. tbody.innerHTML = '';
  5332. (state.routingTables || []).forEach(t => {
  5333. const tr = document.createElement('tr');
  5334. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  5335. tr.innerHTML = `
  5336. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  5337. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  5338. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  5339. `;
  5340. tbody.appendChild(tr);
  5341. });
  5342. }
  5343. function openAddTableModal() {
  5344. document.getElementById('table-modal-name').value = '';
  5345. document.getElementById('table-modal-id').value = '';
  5346. document.getElementById('table-modal-comment').value = '';
  5347. document.getElementById('table-modal').classList.remove('hidden');
  5348. }
  5349. function closeTableModal() {
  5350. document.getElementById('table-modal').classList.add('hidden');
  5351. }
  5352. async function submitSaveTable(e) {
  5353. e.preventDefault();
  5354. const name = document.getElementById('table-modal-name').value.trim();
  5355. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  5356. const comment = document.getElementById('table-modal-comment').value.trim();
  5357. try {
  5358. const res = await fetch(`${API_BASE}/routing/tables`, {
  5359. method: 'POST',
  5360. headers: { 'Content-Type': 'application/json' },
  5361. body: JSON.stringify({ name, table_id: id, comment })
  5362. });
  5363. if (res.ok) {
  5364. showToast('Table Created', `Routing table ${name} registered`, 'success');
  5365. closeTableModal();
  5366. loadRoutes();
  5367. } else {
  5368. const err = await res.json();
  5369. showToast('Error', err.message, 'error');
  5370. }
  5371. } catch (err) {
  5372. showToast('Error', err.message, 'error');
  5373. }
  5374. }
  5375. async function loadDebianConfig() {
  5376. const view = document.getElementById('debian-config-view');
  5377. view.innerText = 'Generating live configuration...';
  5378. try {
  5379. const res = await fetch(`${API_BASE}/debian/config`);
  5380. const data = await res.json();
  5381. view.innerText = data.content || '# Empty config';
  5382. } catch (err) {
  5383. view.innerText = 'Failed to generate Debian network config.';
  5384. }
  5385. }
  5386. async function saveDebianConfig() {
  5387. try {
  5388. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  5389. const data = await res.json();
  5390. if (res.ok) {
  5391. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  5392. loadDebianConfig();
  5393. }
  5394. } catch (err) {
  5395. showToast('Error', err.message, 'error');
  5396. }
  5397. }
  5398. function showToast(title, message, type = 'info') {
  5399. const container = document.getElementById('toast-container');
  5400. const toast = document.createElement('div');
  5401. const borderColors = {
  5402. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  5403. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  5404. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  5405. };
  5406. 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}`;
  5407. toast.innerHTML = `
  5408. <div class="flex-1">
  5409. <div class="font-bold text-xs text-white">${title}</div>
  5410. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${message}</div>
  5411. </div>
  5412. `;
  5413. container.appendChild(toast);
  5414. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  5415. setTimeout(() => {
  5416. toast.classList.add('opacity-0', 'translate-y-2');
  5417. setTimeout(() => toast.remove(), 300);
  5418. }, 4000);
  5419. }
  5420. function formatTraffic(bytesPerSec) {
  5421. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  5422. const kb = bytesPerSec / 1024;
  5423. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  5424. const mb = kb / 1024;
  5425. return `${mb.toFixed(2)} MB/s`;
  5426. }
  5427. function toggleSidebar() {
  5428. const sb = document.getElementById('sidebar');
  5429. sb.classList.toggle('-translate-x-full');
  5430. }
  5431. // ======================== EoIP (Ethernet over IP) ========================
  5432. async function loadEoIP(populate = true) {
  5433. try {
  5434. const res = await fetch(`${API_BASE}/vpn/eoip`);
  5435. const data = await res.json();
  5436. state.eoipTunnels = Array.isArray(data) ? data : [];
  5437. const badge = document.getElementById('eoip-count-badge');
  5438. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  5439. const sideBadge = document.getElementById('badge-eoip-count');
  5440. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  5441. renderEoIPTunnels();
  5442. } catch (err) {
  5443. console.error('Failed to load EoIP:', err);
  5444. }
  5445. }
  5446. function renderEoIPTunnels() {
  5447. const tbody = document.getElementById('eoip-table-body');
  5448. const empty = document.getElementById('eoip-empty');
  5449. if (!tbody) return;
  5450. tbody.innerHTML = '';
  5451. const tunnels = state.eoipTunnels || [];
  5452. if (tunnels.length === 0) {
  5453. empty?.classList.remove('hidden');
  5454. return;
  5455. }
  5456. empty?.classList.add('hidden');
  5457. tunnels.forEach(t => {
  5458. const tr = document.createElement('tr');
  5459. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  5460. tr.innerHTML = `
  5461. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  5462. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  5463. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  5464. <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>
  5465. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  5466. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  5467. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  5468. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  5469. <td class="py-2.5 px-3 font-mono text-[11px]">
  5470. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  5471. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  5472. </td>
  5473. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  5474. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  5475. <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>
  5476. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  5477. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  5478. </td>
  5479. `;
  5480. tbody.appendChild(tr);
  5481. });
  5482. }
  5483. function openAddEoIPModal() {
  5484. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  5485. document.getElementById('eoip-modal-id').value = '';
  5486. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  5487. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  5488. document.getElementById('eoip-modal-remote').value = '';
  5489. document.getElementById('eoip-modal-ip').value = '';
  5490. document.getElementById('eoip-modal-local').value = '';
  5491. document.getElementById('eoip-modal-mac').value = '';
  5492. document.getElementById('eoip-modal-mtu').value = '1500';
  5493. document.getElementById('eoip-modal-comment').value = '';
  5494. document.getElementById('eoip-modal-clampmss').checked = true;
  5495. document.getElementById('eoip-modal-disabled').checked = false;
  5496. document.getElementById('eoip-modal').classList.remove('hidden');
  5497. }
  5498. function openEditEoIPModal(id) {
  5499. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  5500. if (!t) return;
  5501. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  5502. document.getElementById('eoip-modal-id').value = t.id;
  5503. document.getElementById('eoip-modal-name').value = t.name;
  5504. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  5505. document.getElementById('eoip-modal-remote').value = t.remote_address;
  5506. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  5507. document.getElementById('eoip-modal-local').value = t.local_address || '';
  5508. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  5509. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  5510. document.getElementById('eoip-modal-comment').value = t.comment || '';
  5511. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  5512. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  5513. document.getElementById('eoip-modal').classList.remove('hidden');
  5514. }
  5515. function closeEoIPModal() {
  5516. document.getElementById('eoip-modal').classList.add('hidden');
  5517. }
  5518. async function submitSaveEoIP(e) {
  5519. e.preventDefault();
  5520. const id = document.getElementById('eoip-modal-id').value;
  5521. const name = document.getElementById('eoip-modal-name').value.trim();
  5522. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  5523. const remote = document.getElementById('eoip-modal-remote').value.trim();
  5524. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  5525. const local = document.getElementById('eoip-modal-local').value.trim();
  5526. const mac = document.getElementById('eoip-modal-mac').value.trim();
  5527. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  5528. const comment = document.getElementById('eoip-modal-comment').value.trim();
  5529. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  5530. const disabled = document.getElementById('eoip-modal-disabled').checked;
  5531. try {
  5532. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  5533. method: 'POST',
  5534. headers: { 'Content-Type': 'application/json' },
  5535. body: JSON.stringify({
  5536. id,
  5537. name,
  5538. tunnel_id: tunnelId,
  5539. remote_address: remote,
  5540. ip_address: ipAddress,
  5541. local_address: local,
  5542. mac_address: mac,
  5543. mtu,
  5544. clamp_mss: clampMss,
  5545. comment,
  5546. disabled
  5547. })
  5548. });
  5549. if (res.ok) {
  5550. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  5551. closeEoIPModal();
  5552. loadEoIP(false);
  5553. fetchData(false);
  5554. } else {
  5555. const err = await res.json();
  5556. showToast('Error', err.message, 'error');
  5557. }
  5558. } catch (err) {
  5559. showToast('Error', err.message, 'error');
  5560. }
  5561. }
  5562. async function toggleEoIPState(id, disabled) {
  5563. try {
  5564. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  5565. method: 'POST',
  5566. headers: { 'Content-Type': 'application/json' },
  5567. body: JSON.stringify({ disabled })
  5568. });
  5569. if (res.ok) {
  5570. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  5571. loadEoIP(false);
  5572. fetchData(false);
  5573. }
  5574. } catch (err) {
  5575. showToast('Error', err.message, 'error');
  5576. }
  5577. }
  5578. async function deleteEoIP(id) {
  5579. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  5580. try {
  5581. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5582. if (res.ok) {
  5583. showToast('Deleted', 'EoIP tunnel removed', 'success');
  5584. loadEoIP(false);
  5585. fetchData(false);
  5586. }
  5587. } catch (err) {
  5588. showToast('Error', err.message, 'error');
  5589. }
  5590. }
  5591. // ======================== PPP Central Hub & Servers ========================
  5592. function switchPPPSubTab(tab) {
  5593. state.pppSubTab = tab;
  5594. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  5595. tabs.forEach(t => {
  5596. const panel = document.getElementById(`ppp-subtab-${t}`);
  5597. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  5598. if (panel) {
  5599. if (t === tab) panel.classList.remove('hidden');
  5600. else panel.classList.add('hidden');
  5601. }
  5602. if (btn) {
  5603. if (t === tab) {
  5604. 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';
  5605. } else {
  5606. 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';
  5607. }
  5608. }
  5609. });
  5610. const addBtn = document.getElementById('ppp-primary-add-btn');
  5611. if (addBtn) {
  5612. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  5613. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  5614. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  5615. else addBtn.innerHTML = '<span>Save Config</span>';
  5616. }
  5617. if (tab === 'active') loadPPPSessions();
  5618. }
  5619. function openCurrentPPPModal() {
  5620. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  5621. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  5622. else if (state.pppSubTab === 'active') loadPPPSessions();
  5623. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  5624. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  5625. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  5626. }
  5627. async function loadPPP(populateDropdowns = true) {
  5628. await Promise.all([
  5629. loadPPPSecrets(),
  5630. loadPPPProfiles(),
  5631. loadPPPServers(),
  5632. loadPPPSessions()
  5633. ]);
  5634. }
  5635. async function loadPPPSecrets() {
  5636. try {
  5637. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  5638. const data = await res.json();
  5639. state.pppSecrets = Array.isArray(data) ? data : [];
  5640. const b = document.getElementById('ppp-badge-secrets');
  5641. if (b) b.innerText = state.pppSecrets.length;
  5642. const b2 = document.getElementById('secrets-count-badge');
  5643. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  5644. renderPPPSecrets();
  5645. } catch (err) {
  5646. console.error('Failed to load PPP secrets:', err);
  5647. }
  5648. }
  5649. function renderPPPSecrets() {
  5650. const tbody = document.getElementById('secrets-table-body');
  5651. const empty = document.getElementById('secrets-empty');
  5652. if (!tbody) return;
  5653. tbody.innerHTML = '';
  5654. const secrets = state.pppSecrets || [];
  5655. if (secrets.length === 0) {
  5656. empty?.classList.remove('hidden');
  5657. return;
  5658. }
  5659. empty?.classList.add('hidden');
  5660. secrets.forEach(s => {
  5661. const tr = document.createElement('tr');
  5662. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  5663. tr.innerHTML = `
  5664. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  5665. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  5666. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  5667. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  5668. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  5669. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  5670. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  5671. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  5672. <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>
  5673. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  5674. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  5675. </td>
  5676. `;
  5677. tbody.appendChild(tr);
  5678. });
  5679. }
  5680. async function loadPPPProfiles() {
  5681. try {
  5682. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  5683. const data = await res.json();
  5684. state.pppProfiles = Array.isArray(data) ? data : [];
  5685. const b = document.getElementById('ppp-badge-profiles');
  5686. if (b) b.innerText = state.pppProfiles.length;
  5687. const b2 = document.getElementById('profiles-count-badge');
  5688. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  5689. // Populate profile selects across modals
  5690. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  5691. selects.forEach(sid => {
  5692. const el = document.getElementById(sid);
  5693. if (!el) return;
  5694. const cur = el.value;
  5695. el.innerHTML = '';
  5696. state.pppProfiles.forEach(p => {
  5697. const opt = document.createElement('option');
  5698. opt.value = p.name;
  5699. opt.innerText = `${p.name} (${p.remote_address})`;
  5700. if (p.name === cur) opt.selected = true;
  5701. el.appendChild(opt);
  5702. });
  5703. });
  5704. renderPPPProfiles();
  5705. } catch (err) {
  5706. console.error('Failed to load PPP profiles:', err);
  5707. }
  5708. }
  5709. function renderPPPProfiles() {
  5710. const tbody = document.getElementById('profiles-table-body');
  5711. if (!tbody) return;
  5712. tbody.innerHTML = '';
  5713. (state.pppProfiles || []).forEach(p => {
  5714. const isDefault = p.name.startsWith('default');
  5715. const tr = document.createElement('tr');
  5716. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  5717. tr.innerHTML = `
  5718. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  5719. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  5720. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  5721. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  5722. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  5723. <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>
  5724. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  5725. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  5726. ${!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>`}
  5727. </td>
  5728. `;
  5729. tbody.appendChild(tr);
  5730. });
  5731. }
  5732. async function loadPPPServers() {
  5733. try {
  5734. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  5735. fetch(`${API_BASE}/vpn/servers/pppoe`),
  5736. fetch(`${API_BASE}/vpn/servers/pptp`),
  5737. fetch(`${API_BASE}/vpn/servers/l2tp`),
  5738. fetch(`${API_BASE}/vpn/servers/ipsec`)
  5739. ]);
  5740. if (pppoeRes.ok) {
  5741. state.pppoeServer = await pppoeRes.json();
  5742. const s = state.pppoeServer;
  5743. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  5744. document.getElementById('pppoe-server-name').value = s.service_name || 'proxmox-pppoe';
  5745. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  5746. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  5747. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  5748. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  5749. const pill = document.getElementById('pppoe-server-status-pill');
  5750. if (pill) {
  5751. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  5752. 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';
  5753. }
  5754. setDotBadge('ppp-badge-pppoe-state', s.running);
  5755. }
  5756. if (pptpRes.ok) {
  5757. state.pptpServer = await pptpRes.json();
  5758. const s = state.pptpServer;
  5759. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  5760. document.getElementById('pptp-server-port').value = s.port || 1723;
  5761. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  5762. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  5763. const pill = document.getElementById('pptp-server-status-pill');
  5764. if (pill) {
  5765. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  5766. 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';
  5767. }
  5768. setDotBadge('ppp-badge-pptp-state', s.running);
  5769. }
  5770. if (l2tpRes.ok) {
  5771. state.l2tpServer = await l2tpRes.json();
  5772. const s = state.l2tpServer;
  5773. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  5774. document.getElementById('l2tp-server-port').value = s.port || 1701;
  5775. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  5776. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  5777. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  5778. const pill = document.getElementById('l2tp-server-status-pill');
  5779. if (pill) {
  5780. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  5781. 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';
  5782. }
  5783. setDotBadge('ppp-badge-l2tp-state', s.running);
  5784. }
  5785. if (ipsecRes.ok) {
  5786. state.ipsecServer = await ipsecRes.json();
  5787. const s = state.ipsecServer;
  5788. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  5789. if (modalEn) modalEn.checked = !!s.enabled;
  5790. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  5791. if (modalPsk) modalPsk.value = s.preshared_key || '';
  5792. const modalPool = document.getElementById('modal-ipsec-server-pool');
  5793. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  5794. const modalDns = document.getElementById('modal-ipsec-server-dns');
  5795. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  5796. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  5797. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  5798. const pill = document.getElementById('modal-ipsec-server-status');
  5799. if (pill) {
  5800. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  5801. 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';
  5802. }
  5803. }
  5804. } catch (err) {
  5805. console.error('Failed to load VPN servers:', err);
  5806. }
  5807. }
  5808. async function loadPPPSessions() {
  5809. try {
  5810. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  5811. const data = await res.json();
  5812. state.pppActiveSessions = Array.isArray(data) ? data : [];
  5813. const b = document.getElementById('ppp-badge-active');
  5814. if (b) b.innerText = state.pppActiveSessions.length;
  5815. const sideB = document.getElementById('badge-ppp-sessions');
  5816. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  5817. renderPPPSessions();
  5818. } catch (err) {
  5819. console.error('Failed to load active PPP sessions:', err);
  5820. }
  5821. }
  5822. function renderPPPSessions() {
  5823. const tbody = document.getElementById('active-ppp-table-body');
  5824. const empty = document.getElementById('active-ppp-empty');
  5825. if (!tbody) return;
  5826. tbody.innerHTML = '';
  5827. const list = state.pppActiveSessions || [];
  5828. if (list.length === 0) {
  5829. empty?.classList.remove('hidden');
  5830. return;
  5831. }
  5832. empty?.classList.add('hidden');
  5833. list.forEach(s => {
  5834. const tr = document.createElement('tr');
  5835. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  5836. tr.innerHTML = `
  5837. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  5838. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  5839. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  5840. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  5841. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  5842. <td class="py-2.5 px-3 text-[11px]">
  5843. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  5844. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  5845. </td>
  5846. <td class="py-2.5 px-3 text-right font-sans">
  5847. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  5848. </td>
  5849. `;
  5850. tbody.appendChild(tr);
  5851. });
  5852. }
  5853. async function disconnectPPPSession(iface) {
  5854. if (!confirm(`Disconnect session ${iface}?`)) return;
  5855. try {
  5856. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  5857. if (res.ok) {
  5858. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  5859. loadPPPSessions();
  5860. }
  5861. } catch (err) {
  5862. showToast('Error', err.message, 'error');
  5863. }
  5864. }
  5865. // PPP Secret Modal handlers
  5866. function openAddPPPSecretModal() {
  5867. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  5868. document.getElementById('secret-modal-id').value = '';
  5869. document.getElementById('secret-modal-name').value = '';
  5870. document.getElementById('secret-modal-password').value = '';
  5871. document.getElementById('secret-modal-service').value = 'any';
  5872. document.getElementById('secret-modal-profile').value = 'default';
  5873. document.getElementById('secret-modal-local').value = '';
  5874. document.getElementById('secret-modal-remote').value = '';
  5875. document.getElementById('secret-modal-comment').value = '';
  5876. document.getElementById('secret-modal-disabled').checked = false;
  5877. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  5878. }
  5879. function openEditPPPSecretModal(id) {
  5880. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  5881. if (!s) return;
  5882. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  5883. document.getElementById('secret-modal-id').value = s.id;
  5884. document.getElementById('secret-modal-name').value = s.name;
  5885. document.getElementById('secret-modal-password').value = s.password;
  5886. document.getElementById('secret-modal-service').value = s.service || 'any';
  5887. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  5888. document.getElementById('secret-modal-local').value = s.local_address || '';
  5889. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  5890. document.getElementById('secret-modal-comment').value = s.comment || '';
  5891. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  5892. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  5893. }
  5894. function closePPPSecretModal() {
  5895. document.getElementById('ppp-secret-modal').classList.add('hidden');
  5896. }
  5897. async function submitSavePPPSecret(e) {
  5898. e.preventDefault();
  5899. const id = document.getElementById('secret-modal-id').value;
  5900. const name = document.getElementById('secret-modal-name').value.trim();
  5901. const password = document.getElementById('secret-modal-password').value.trim();
  5902. const service = document.getElementById('secret-modal-service').value;
  5903. const profile = document.getElementById('secret-modal-profile').value;
  5904. const local = document.getElementById('secret-modal-local').value.trim();
  5905. const remote = document.getElementById('secret-modal-remote').value.trim();
  5906. const comment = document.getElementById('secret-modal-comment').value.trim();
  5907. const disabled = document.getElementById('secret-modal-disabled').checked;
  5908. try {
  5909. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  5910. method: 'POST',
  5911. headers: { 'Content-Type': 'application/json' },
  5912. body: JSON.stringify({
  5913. id,
  5914. name,
  5915. password,
  5916. service,
  5917. profile,
  5918. local_address: local,
  5919. remote_address: remote,
  5920. comment,
  5921. disabled
  5922. })
  5923. });
  5924. if (res.ok) {
  5925. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  5926. closePPPSecretModal();
  5927. loadPPPSecrets();
  5928. } else {
  5929. const err = await res.json();
  5930. showToast('Error', err.message, 'error');
  5931. }
  5932. } catch (err) {
  5933. showToast('Error', err.message, 'error');
  5934. }
  5935. }
  5936. async function togglePPPSecretState(id, disabled) {
  5937. try {
  5938. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  5939. method: 'POST',
  5940. headers: { 'Content-Type': 'application/json' },
  5941. body: JSON.stringify({ disabled })
  5942. });
  5943. if (res.ok) {
  5944. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  5945. loadPPPSecrets();
  5946. }
  5947. } catch (err) {
  5948. showToast('Error', err.message, 'error');
  5949. }
  5950. }
  5951. async function deletePPPSecret(id) {
  5952. if (!confirm('Are you sure you want to delete this secret account?')) return;
  5953. try {
  5954. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5955. if (res.ok) {
  5956. showToast('Deleted', 'Secret account removed', 'success');
  5957. loadPPPSecrets();
  5958. }
  5959. } catch (err) {
  5960. showToast('Error', err.message, 'error');
  5961. }
  5962. }
  5963. // PPP Profile Modal handlers
  5964. function openAddPPPProfileModal() {
  5965. document.getElementById('profile-modal-name').value = '';
  5966. document.getElementById('profile-modal-local').value = '10.10.10.1';
  5967. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  5968. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  5969. document.getElementById('profile-modal-encryption').value = 'required';
  5970. document.getElementById('profile-modal-onlyone').checked = true;
  5971. document.getElementById('profile-modal-comment').value = '';
  5972. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  5973. }
  5974. function closePPPProfileModal() {
  5975. document.getElementById('ppp-profile-modal').classList.add('hidden');
  5976. }
  5977. async function submitSavePPPProfile(e) {
  5978. e.preventDefault();
  5979. const name = document.getElementById('profile-modal-name').value.trim();
  5980. const local = document.getElementById('profile-modal-local').value.trim();
  5981. const remote = document.getElementById('profile-modal-remote').value.trim();
  5982. const dns = document.getElementById('profile-modal-dns').value.trim();
  5983. const enc = document.getElementById('profile-modal-encryption').value;
  5984. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  5985. const comment = document.getElementById('profile-modal-comment').value.trim();
  5986. try {
  5987. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  5988. method: 'POST',
  5989. headers: { 'Content-Type': 'application/json' },
  5990. body: JSON.stringify({
  5991. id: name,
  5992. name,
  5993. local_address: local,
  5994. remote_address: remote,
  5995. dns_servers: dns,
  5996. use_encryption: enc,
  5997. only_one: onlyone,
  5998. comment
  5999. })
  6000. });
  6001. if (res.ok) {
  6002. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  6003. closePPPProfileModal();
  6004. loadPPPProfiles();
  6005. } else {
  6006. const err = await res.json();
  6007. showToast('Error', err.message, 'error');
  6008. }
  6009. } catch (err) {
  6010. showToast('Error', err.message, 'error');
  6011. }
  6012. }
  6013. async function deletePPPProfile(name) {
  6014. if (!confirm(`Delete PPP profile ${name}?`)) return;
  6015. try {
  6016. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  6017. if (res.ok) {
  6018. showToast('Deleted', 'Profile removed', 'success');
  6019. loadPPPProfiles();
  6020. } else {
  6021. const err = await res.json();
  6022. showToast('Error', err.message, 'error');
  6023. }
  6024. } catch (err) {
  6025. showToast('Error', err.message, 'error');
  6026. }
  6027. }
  6028. // Server Config submissions
  6029. async function savePPPoEServerConfig(e) {
  6030. e.preventDefault();
  6031. const enabled = document.getElementById('pppoe-server-enabled').checked;
  6032. const name = document.getElementById('pppoe-server-name').value.trim();
  6033. const iface = document.getElementById('pppoe-server-iface').value;
  6034. const profile = document.getElementById('pppoe-server-profile').value;
  6035. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  6036. const onesession = document.getElementById('pppoe-server-onesession').checked;
  6037. try {
  6038. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  6039. method: 'POST',
  6040. headers: { 'Content-Type': 'application/json' },
  6041. body: JSON.stringify({
  6042. enabled,
  6043. service_name: name,
  6044. interface: iface,
  6045. default_profile: profile,
  6046. max_mtu: mtu,
  6047. max_mru: mtu,
  6048. one_session_per_host: onesession
  6049. })
  6050. });
  6051. if (res.ok) {
  6052. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  6053. loadPPPServers();
  6054. fetchData(false);
  6055. } else {
  6056. const err = await res.json();
  6057. showToast('Error', err.message, 'error');
  6058. }
  6059. } catch (err) {
  6060. showToast('Error', err.message, 'error');
  6061. }
  6062. }
  6063. async function savePPTPServerConfig(e) {
  6064. e.preventDefault();
  6065. const enabled = document.getElementById('pptp-server-enabled').checked;
  6066. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  6067. const profile = document.getElementById('pptp-server-profile').value;
  6068. const mppe = document.getElementById('pptp-server-mppe').checked;
  6069. try {
  6070. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  6071. method: 'POST',
  6072. headers: { 'Content-Type': 'application/json' },
  6073. body: JSON.stringify({
  6074. enabled,
  6075. port,
  6076. default_profile: profile,
  6077. require_mppe: mppe
  6078. })
  6079. });
  6080. if (res.ok) {
  6081. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  6082. loadPPPServers();
  6083. fetchData(false);
  6084. } else {
  6085. const err = await res.json();
  6086. showToast('Error', err.message, 'error');
  6087. }
  6088. } catch (err) {
  6089. showToast('Error', err.message, 'error');
  6090. }
  6091. }
  6092. async function saveL2TPServerConfig(e) {
  6093. e.preventDefault();
  6094. const enabled = document.getElementById('l2tp-server-enabled').checked;
  6095. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  6096. const profile = document.getElementById('l2tp-server-profile').value;
  6097. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  6098. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  6099. try {
  6100. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  6101. method: 'POST',
  6102. headers: { 'Content-Type': 'application/json' },
  6103. body: JSON.stringify({
  6104. enabled,
  6105. port,
  6106. default_profile: profile,
  6107. use_ipsec: useipsec,
  6108. ipsec_secret: psk
  6109. })
  6110. });
  6111. if (res.ok) {
  6112. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  6113. loadPPPServers();
  6114. fetchData(false);
  6115. } else {
  6116. const err = await res.json();
  6117. showToast('Error', err.message, 'error');
  6118. }
  6119. } catch (err) {
  6120. showToast('Error', err.message, 'error');
  6121. }
  6122. }
  6123. // IPSec Server Modal
  6124. function openIPSecServerModal() {
  6125. loadPPPServers();
  6126. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  6127. }
  6128. function closeIPSecServerModal() {
  6129. document.getElementById('ipsec-server-modal').classList.add('hidden');
  6130. }
  6131. async function submitSaveIPSecServer(e) {
  6132. e.preventDefault();
  6133. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  6134. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  6135. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  6136. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  6137. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  6138. try {
  6139. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  6140. method: 'POST',
  6141. headers: { 'Content-Type': 'application/json' },
  6142. body: JSON.stringify({
  6143. enabled,
  6144. preshared_key: psk,
  6145. pool_address: pool,
  6146. dns_servers: dns,
  6147. local_subnet: subnet
  6148. })
  6149. });
  6150. if (res.ok) {
  6151. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  6152. closeIPSecServerModal();
  6153. loadPPPServers();
  6154. fetchData(false);
  6155. } else {
  6156. const err = await res.json();
  6157. showToast('Error', err.message, 'error');
  6158. }
  6159. } catch (err) {
  6160. showToast('Error', err.message, 'error');
  6161. }
  6162. }
  6163. // WireGuard Client Config Viewer
  6164. let currentWGClientConf = '';
  6165. async function openWGClientConfModal(iface, clientIP) {
  6166. try {
  6167. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  6168. method: 'POST',
  6169. headers: { 'Content-Type': 'application/json' },
  6170. body: JSON.stringify({
  6171. interface: iface,
  6172. address: clientIP || '10.10.0.2/32',
  6173. dns: '1.1.1.1, 8.8.8.8'
  6174. })
  6175. });
  6176. if (res.ok) {
  6177. const data = await res.json();
  6178. currentWGClientConf = data.config;
  6179. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  6180. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  6181. } else {
  6182. const err = await res.json();
  6183. showToast('Error', err.message, 'error');
  6184. }
  6185. } catch (err) {
  6186. showToast('Error', err.message, 'error');
  6187. }
  6188. }
  6189. function closeWGClientConfModal() {
  6190. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  6191. }
  6192. function copyWGClientConf() {
  6193. if (!currentWGClientConf) return;
  6194. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  6195. }
  6196. function downloadWGClientConf() {
  6197. if (!currentWGClientConf) return;
  6198. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  6199. const a = document.createElement('a');
  6200. a.href = URL.createObjectURL(blob);
  6201. a.download = 'wireguard-client.conf';
  6202. document.body.appendChild(a);
  6203. a.click();
  6204. document.body.removeChild(a);
  6205. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  6206. }
  6207. // =========================================================================
  6208. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  6209. // =========================================================================
  6210. state.activeDynSubTab = 'bgp-peers';
  6211. state.activeBgpSubTab = 'bgp-peers';
  6212. state.activeOspfTab = 'instances';
  6213. state.bgpInstance = null;
  6214. state.bgpPeers = [];
  6215. state.bgpNets = [];
  6216. state.bgpRoutes = [];
  6217. state.ospfInstance = null;
  6218. state.ospfInstances = [];
  6219. state.ospfAreas = [];
  6220. state.ospfAreaRanges = [];
  6221. state.ospfTemplates = [];
  6222. state.ospfLiveInterfaces = [];
  6223. state.ospfStaticNbrs = [];
  6224. state.ospfNeighbors = [];
  6225. state.ospfLSA = [];
  6226. state.ospfRoutes = [];
  6227. state.selectedOspfRow = {
  6228. instances: null,
  6229. areas: null,
  6230. 'area-ranges': null,
  6231. templates: null,
  6232. interfaces: null,
  6233. 'static-nbrs': null,
  6234. neighbors: null,
  6235. lsa: null,
  6236. };
  6237. state.ospfSort = {
  6238. instances: { col: 'name', asc: true },
  6239. areas: { col: 'name', asc: true },
  6240. ranges: { col: 'area', asc: true },
  6241. templates: { col: 'interfaces', asc: true },
  6242. live_ifaces: { col: 'interface', asc: true },
  6243. snbrs: { col: 'address', asc: true },
  6244. neighbors: { col: 'address', asc: true },
  6245. lsa: { col: 'instance', asc: true },
  6246. };
  6247. function switchBgpSubTab(subTab) {
  6248. state.activeBgpSubTab = subTab;
  6249. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes'];
  6250. tabs.forEach(t => {
  6251. const el = document.getElementById(`dyn-subtab-${t}`);
  6252. const btn = document.getElementById(`bgp-subtab-btn-${t}`);
  6253. if (el) el.classList.toggle('hidden', t !== subTab);
  6254. if (btn) {
  6255. if (t === subTab) {
  6256. 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';
  6257. } else {
  6258. 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';
  6259. }
  6260. }
  6261. });
  6262. }
  6263. function switchOspfTab(tabName) {
  6264. state.activeOspfTab = tabName;
  6265. const tabs = ['instances', 'areas', 'area-ranges', 'templates', 'interfaces', 'static-nbrs', 'neighbors', 'lsa'];
  6266. tabs.forEach(t => {
  6267. const pane = document.getElementById(`ospf-pane-${t}`);
  6268. const btn = document.getElementById(`ospf-tab-btn-${t}`);
  6269. if (pane) pane.classList.toggle('hidden', t !== tabName);
  6270. if (btn) {
  6271. if (t === tabName) {
  6272. btn.className = 'px-3 py-2 text-xs font-semibold border-b-2 border-sky-500 text-white transition flex items-center gap-1.5 whitespace-nowrap';
  6273. } else {
  6274. btn.className = 'px-3 py-2 text-xs font-semibold border-b-2 border-transparent text-slate-400 hover:text-white transition flex items-center gap-1.5 whitespace-nowrap';
  6275. }
  6276. }
  6277. });
  6278. }
  6279. function switchOspfSubTab(tab) {
  6280. // Legacy alias
  6281. if (tab === 'ospf-ifaces') switchOspfTab('templates');
  6282. else if (tab === 'ospf-areas') switchOspfTab('areas');
  6283. else if (tab === 'ospf-nbrs') switchOspfTab('neighbors');
  6284. else switchOspfTab('instances');
  6285. }
  6286. function switchDynSubTab(subTab) {
  6287. if (subTab.startsWith('bgp')) {
  6288. if (state.activeTab !== 'bgp') navigate('bgp');
  6289. switchBgpSubTab(subTab);
  6290. } else if (subTab.startsWith('ospf')) {
  6291. if (state.activeTab !== 'ospf') navigate('ospf');
  6292. switchOspfTab('instances');
  6293. }
  6294. }
  6295. async function loadDynamicRouting(showToastMsg = false) {
  6296. try {
  6297. const fetchSafeJson = async (url) => {
  6298. try {
  6299. const r = await fetch(url);
  6300. return r.ok ? await r.json() : null;
  6301. } catch (e) {
  6302. return null;
  6303. }
  6304. };
  6305. const [
  6306. sum, bgpInst, bgpPeers, bgpNets, bgpRoutes,
  6307. ospfInsts, ospfAreas, ospfRanges, ospfTemplates, ospfLiveIfaces, ospfStaticNbrs, ospfNbrs, ospfLsa, filters
  6308. ] = await Promise.all([
  6309. fetchSafeJson(`${API_BASE}/routing/dynamic/summary`),
  6310. fetchSafeJson(`${API_BASE}/routing/bgp/instance`),
  6311. fetchSafeJson(`${API_BASE}/routing/bgp/peers`),
  6312. fetchSafeJson(`${API_BASE}/routing/bgp/networks`),
  6313. fetchSafeJson(`${API_BASE}/routing/bgp/routes`),
  6314. fetchSafeJson(`${API_BASE}/routing/ospf/instances`),
  6315. fetchSafeJson(`${API_BASE}/routing/ospf/areas`),
  6316. fetchSafeJson(`${API_BASE}/routing/ospf/area-ranges`),
  6317. fetchSafeJson(`${API_BASE}/routing/ospf/templates`),
  6318. fetchSafeJson(`${API_BASE}/routing/ospf/interfaces-live`),
  6319. fetchSafeJson(`${API_BASE}/routing/ospf/static-neighbors`),
  6320. fetchSafeJson(`${API_BASE}/routing/ospf/neighbors`),
  6321. fetchSafeJson(`${API_BASE}/routing/ospf/lsa`),
  6322. fetchSafeJson(`${API_BASE}/routing/filters`)
  6323. ]);
  6324. if (sum) state.dynSummary = sum;
  6325. if (bgpInst) state.bgpInstance = bgpInst;
  6326. if (bgpPeers) state.bgpPeers = bgpPeers;
  6327. if (bgpNets) state.bgpNets = bgpNets;
  6328. if (bgpRoutes) state.bgpRoutes = bgpRoutes;
  6329. if (ospfInsts) state.ospfInstances = ospfInsts;
  6330. if (ospfAreas) state.ospfAreas = ospfAreas;
  6331. if (ospfRanges) state.ospfAreaRanges = ospfRanges;
  6332. if (ospfTemplates) state.ospfTemplates = ospfTemplates;
  6333. if (ospfLiveIfaces) state.ospfLiveInterfaces = ospfLiveIfaces;
  6334. if (ospfStaticNbrs) state.ospfStaticNbrs = ospfStaticNbrs;
  6335. if (ospfNbrs) state.ospfNeighbors = ospfNbrs;
  6336. if (ospfLsa) state.ospfLSA = ospfLsa;
  6337. if (filters) state.routingFilters = filters;
  6338. try { renderBgpStatusPill(); } catch(e) { console.error('renderBgpStatusPill error:', e); }
  6339. try { renderBgpPeers(); } catch(e) { console.error('renderBgpPeers error:', e); }
  6340. try { renderBgpNetworks(); } catch(e) { console.error('renderBgpNetworks error:', e); }
  6341. try { renderBgpRoutes(); } catch(e) { console.error('renderBgpRoutes error:', e); }
  6342. try { renderOspfInstances(); } catch(e) { console.error('renderOspfInstances error:', e); }
  6343. try { renderOspfAreas(); } catch(e) { console.error('renderOspfAreas error:', e); }
  6344. try { renderOspfAreaRanges(); } catch(e) { console.error('renderOspfAreaRanges error:', e); }
  6345. try { renderOspfTemplates(); } catch(e) { console.error('renderOspfTemplates error:', e); }
  6346. try { renderOspfLiveInterfaces(); } catch(e) { console.error('renderOspfLiveInterfaces error:', e); }
  6347. try { renderOspfStaticNbrs(); } catch(e) { console.error('renderOspfStaticNbrs error:', e); }
  6348. try { renderOspfNeighbors(); } catch(e) { console.error('renderOspfNeighbors error:', e); }
  6349. try { renderOspfLSA(); } catch(e) { console.error('renderOspfLSA error:', e); }
  6350. try { renderRoutingFilters(); } catch(e) { console.error('renderRoutingFilters error:', e); }
  6351. try { updateBadges(); } catch(e) { console.error('updateBadges error:', e); }
  6352. if (showToastMsg) showToast('Refreshed', 'Dynamic routing telemetry updated', 'info');
  6353. } catch (err) {
  6354. console.error('Failed to load dynamic routing:', err);
  6355. if (showToastMsg) showToast('Notice', 'Unable to refresh dynamic routing telemetry', 'warning');
  6356. }
  6357. }
  6358. async function loadOspfAll() {
  6359. await loadDynamicRouting(true);
  6360. }
  6361. function renderBgpStatusPill() {
  6362. const pill = document.getElementById('bgp-live-status-pill');
  6363. if (!pill) return;
  6364. const inst = state.bgpInstance;
  6365. if (!inst || !inst.enabled) {
  6366. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  6367. pill.innerText = 'BGP DISABLED';
  6368. } else if (inst.running) {
  6369. 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';
  6370. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  6371. } else {
  6372. 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';
  6373. pill.innerText = 'BGP STARTING...';
  6374. }
  6375. }
  6376. function renderBgpPeers() {
  6377. const tbody = document.getElementById('bgp-peers-table-body');
  6378. if (!tbody) return;
  6379. const empty = document.getElementById('bgp-peers-empty');
  6380. const countBadge = document.getElementById('bgp-peers-count-badge');
  6381. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  6382. const peers = state.bgpPeers || [];
  6383. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  6384. if (navBadge) navBadge.innerText = peers.length;
  6385. if (peers.length === 0) {
  6386. tbody.innerHTML = '';
  6387. if (empty) empty.classList.remove('hidden');
  6388. return;
  6389. }
  6390. if (empty) empty.classList.add('hidden');
  6391. tbody.innerHTML = peers.map(p => {
  6392. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  6393. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  6394. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  6395. let stateBadge = '';
  6396. if (p.disabled) {
  6397. 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>';
  6398. } else if (p.state === 'Established') {
  6399. 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>';
  6400. } else if (p.state === 'Connect' || p.state === 'Active') {
  6401. 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>`;
  6402. } else {
  6403. 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>`;
  6404. }
  6405. return `
  6406. <tr class="hover:bg-slate-800/40 transition">
  6407. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  6408. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  6409. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  6410. <td class="py-2.5 px-3">
  6411. <div class="font-bold text-slate-200">AS ${p.remote_as}</div>
  6412. ${p.local_as ? `<div class="text-[10px] text-purple-400 font-mono font-semibold" title="Custom Multi-Instance AS">Local: AS ${p.local_as}</div>` : `<div class="text-[10px] text-slate-500 font-mono">Global AS</div>`}
  6413. </td>
  6414. <td class="py-2.5 px-3">${stateBadge}</td>
  6415. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  6416. <td class="py-2.5 px-3 text-slate-300">
  6417. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  6418. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  6419. </td>
  6420. <td class="py-2.5 px-3 font-mono text-[11px] whitespace-nowrap">
  6421. ${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> ` : ''}
  6422. ${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>` : ''}
  6423. ${!p.in_filter && !p.out_filter ? '<span class="text-slate-600">-</span>' : ''}
  6424. </td>
  6425. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  6426. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  6427. <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'}">
  6428. ${p.disabled ? 'Enable' : 'Disable'}
  6429. </button>
  6430. <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">
  6431. Edit
  6432. </button>
  6433. <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">
  6434. Delete
  6435. </button>
  6436. </td>
  6437. </tr>
  6438. `;
  6439. }).join('');
  6440. }
  6441. function renderBgpNetworks() {
  6442. const tbody = document.getElementById('bgp-nets-table-body');
  6443. if (!tbody) return;
  6444. const empty = document.getElementById('bgp-nets-empty');
  6445. const countBadge = document.getElementById('bgp-nets-count-badge');
  6446. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  6447. const nets = state.bgpNets || [];
  6448. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  6449. if (navBadge) navBadge.innerText = nets.length;
  6450. if (nets.length === 0) {
  6451. tbody.innerHTML = '';
  6452. if (empty) empty.classList.remove('hidden');
  6453. return;
  6454. }
  6455. if (empty) empty.classList.add('hidden');
  6456. tbody.innerHTML = nets.map(n => `
  6457. <tr class="hover:bg-slate-800/40 transition">
  6458. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  6459. <td class="py-2.5 px-3">
  6460. ${n.disabled
  6461. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  6462. : '<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>'}
  6463. </td>
  6464. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  6465. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  6466. <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">
  6467. Delete
  6468. </button>
  6469. </td>
  6470. </tr>
  6471. `).join('');
  6472. }
  6473. function renderBgpRoutes() {
  6474. const tbody = document.getElementById('bgp-routes-table-body');
  6475. if (!tbody) return;
  6476. const empty = document.getElementById('bgp-routes-empty');
  6477. const countBadge = document.getElementById('bgp-routes-count-badge');
  6478. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  6479. const routes = state.bgpRoutes || [];
  6480. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  6481. if (navBadge) navBadge.innerText = routes.length;
  6482. if (routes.length === 0) {
  6483. tbody.innerHTML = '';
  6484. if (empty) empty.classList.remove('hidden');
  6485. return;
  6486. }
  6487. if (empty) empty.classList.add('hidden');
  6488. tbody.innerHTML = routes.map(r => `
  6489. <tr class="hover:bg-slate-800/40 transition">
  6490. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  6491. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  6492. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  6493. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  6494. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  6495. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  6496. </tr>
  6497. `).join('');
  6498. }
  6499. // =========================================================================
  6500. // ROUTEROS v7 OSPF TABLE RENDERING & SORTING
  6501. // =========================================================================
  6502. function sortOspfTable(tab, col) {
  6503. if (!state.ospfSort) state.ospfSort = {};
  6504. if (!state.ospfSort[tab]) state.ospfSort[tab] = { col: col, asc: true };
  6505. if (state.ospfSort[tab].col === col) {
  6506. state.ospfSort[tab].asc = !state.ospfSort[tab].asc;
  6507. } else {
  6508. state.ospfSort[tab].col = col;
  6509. state.ospfSort[tab].asc = true;
  6510. }
  6511. const asc = state.ospfSort[tab].asc;
  6512. let list = [];
  6513. if (tab === 'instances') list = state.ospfInstances || [];
  6514. else if (tab === 'areas') list = state.ospfAreas || [];
  6515. else if (tab === 'ranges') list = state.ospfAreaRanges || [];
  6516. else if (tab === 'templates') list = state.ospfTemplates || [];
  6517. else if (tab === 'live_ifaces') list = state.ospfLiveInterfaces || [];
  6518. else if (tab === 'snbrs') list = state.ospfStaticNbrs || [];
  6519. else if (tab === 'neighbors') list = state.ospfNeighbors || [];
  6520. else if (tab === 'lsa') list = state.ospfLSA || [];
  6521. list.sort((a, b) => {
  6522. let valA = a[col] ?? '';
  6523. let valB = b[col] ?? '';
  6524. if (typeof valA === 'number' && typeof valB === 'number') {
  6525. return asc ? valA - valB : valB - valA;
  6526. }
  6527. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  6528. });
  6529. if (tab === 'instances') renderOspfInstances();
  6530. else if (tab === 'areas') renderOspfAreas();
  6531. else if (tab === 'ranges') renderOspfAreaRanges();
  6532. else if (tab === 'templates') renderOspfTemplates();
  6533. else if (tab === 'live_ifaces') renderOspfLiveInterfaces();
  6534. else if (tab === 'snbrs') renderOspfStaticNbrs();
  6535. else if (tab === 'neighbors') renderOspfNeighbors();
  6536. else if (tab === 'lsa') renderOspfLSA();
  6537. }
  6538. function selectOspfRow(tab, id) {
  6539. if (!state.selectedOspfRow) state.selectedOspfRow = {};
  6540. state.selectedOspfRow[tab] = id;
  6541. if (tab === 'instances') {
  6542. renderOspfInstances();
  6543. const btnEn = document.getElementById('btn-ospf-inst-enable');
  6544. const btnDis = document.getElementById('btn-ospf-inst-disable');
  6545. const btnRem = document.getElementById('btn-ospf-inst-remove');
  6546. const btnCom = document.getElementById('btn-ospf-inst-comment');
  6547. if (btnEn) btnEn.disabled = false;
  6548. if (btnDis) btnDis.disabled = false;
  6549. if (btnRem) btnRem.disabled = false;
  6550. if (btnCom) btnCom.disabled = false;
  6551. } else if (tab === 'areas') {
  6552. renderOspfAreas();
  6553. const btnEn = document.getElementById('btn-ospf-area-enable');
  6554. const btnDis = document.getElementById('btn-ospf-area-disable');
  6555. const btnRem = document.getElementById('btn-ospf-area-remove');
  6556. const btnCom = document.getElementById('btn-ospf-area-comment');
  6557. if (btnEn) btnEn.disabled = false;
  6558. if (btnDis) btnDis.disabled = false;
  6559. if (btnRem) btnRem.disabled = false;
  6560. if (btnCom) btnCom.disabled = false;
  6561. } else if (tab === 'ranges') {
  6562. renderOspfAreaRanges();
  6563. const btnEn = document.getElementById('btn-ospf-range-enable');
  6564. const btnDis = document.getElementById('btn-ospf-range-disable');
  6565. const btnRem = document.getElementById('btn-ospf-range-remove');
  6566. const btnCom = document.getElementById('btn-ospf-range-comment');
  6567. if (btnEn) btnEn.disabled = false;
  6568. if (btnDis) btnDis.disabled = false;
  6569. if (btnRem) btnRem.disabled = false;
  6570. if (btnCom) btnCom.disabled = false;
  6571. } else if (tab === 'templates') {
  6572. renderOspfTemplates();
  6573. const btnEn = document.getElementById('btn-ospf-tmpl-enable');
  6574. const btnDis = document.getElementById('btn-ospf-tmpl-disable');
  6575. const btnRem = document.getElementById('btn-ospf-tmpl-remove');
  6576. const btnCom = document.getElementById('btn-ospf-tmpl-comment');
  6577. if (btnEn) btnEn.disabled = false;
  6578. if (btnDis) btnDis.disabled = false;
  6579. if (btnRem) btnRem.disabled = false;
  6580. if (btnCom) btnCom.disabled = false;
  6581. } else if (tab === 'snbrs') {
  6582. renderOspfStaticNbrs();
  6583. const btnEn = document.getElementById('btn-ospf-snbr-enable');
  6584. const btnDis = document.getElementById('btn-ospf-snbr-disable');
  6585. const btnRem = document.getElementById('btn-ospf-snbr-remove');
  6586. const btnCom = document.getElementById('btn-ospf-snbr-comment');
  6587. if (btnEn) btnEn.disabled = false;
  6588. if (btnDis) btnDis.disabled = false;
  6589. if (btnRem) btnRem.disabled = false;
  6590. if (btnCom) btnCom.disabled = false;
  6591. }
  6592. }
  6593. // TAB 1: INSTANCES
  6594. function renderOspfInstances() {
  6595. const tbody = document.getElementById('ospf-instances-table-body');
  6596. if (!tbody) return;
  6597. const countEl = document.getElementById('ospf-instances-footer-count');
  6598. const filter = (document.getElementById('filter-ospf-instances')?.value || '').toLowerCase();
  6599. let list = state.ospfInstances || [];
  6600. if (filter) {
  6601. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.router_id || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  6602. }
  6603. if (countEl) countEl.innerText = list.length;
  6604. const selId = state.selectedOspfRow?.instances;
  6605. tbody.innerHTML = list.map((inst, idx) => {
  6606. const isSel = inst.id === selId;
  6607. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  6608. const flagD = inst.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  6609. return `
  6610. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('instances', '${inst.id}')" ondblclick="openEditOspfInstanceModal('${inst.id}')">
  6611. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  6612. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  6613. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  6614. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  6615. <span class="text-sky-400">↳</span> <span>${escapeHtml(inst.name || 'Default')}</span>
  6616. </td>
  6617. <td class="py-1.5 px-3">${inst.version || 2}</td>
  6618. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(inst.vrf || 'main')}</td>
  6619. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(inst.router_id || '192.168.131.56')}</td>
  6620. </tr>
  6621. `;
  6622. }).join('');
  6623. }
  6624. // TAB 2: AREAS
  6625. function renderOspfAreas() {
  6626. const tbody = document.getElementById('ospf-areas-table-body');
  6627. if (!tbody) return;
  6628. const countEl = document.getElementById('ospf-areas-footer-count');
  6629. const filter = (document.getElementById('filter-ospf-areas')?.value || '').toLowerCase();
  6630. let list = state.ospfAreas || [];
  6631. if (filter) {
  6632. list = list.filter(a => (a.name || '').toLowerCase().includes(filter) || (a.area_id || '').toLowerCase().includes(filter) || (a.comment || '').toLowerCase().includes(filter));
  6633. }
  6634. if (countEl) countEl.innerText = list.length;
  6635. const selId = state.selectedOspfRow?.areas;
  6636. tbody.innerHTML = list.map((a, idx) => {
  6637. const isSel = a.id === selId;
  6638. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  6639. const flagD = a.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  6640. return `
  6641. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('areas', '${a.id}')" ondblclick="openEditOspfAreaModal('${a.id}')">
  6642. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  6643. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🌐'}</td>
  6644. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(a.comment || '')}</td>
  6645. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  6646. <span class="text-sky-400">↳</span> <span>${escapeHtml(a.name || 'Default')}</span>
  6647. </td>
  6648. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(a.instance || 'Default')}</td>
  6649. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(a.area_id || '0.0.0.0')}</td>
  6650. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(a.area_type || 'default')}</td>
  6651. </tr>
  6652. `;
  6653. }).join('');
  6654. }
  6655. // TAB 3: AREA RANGES
  6656. function renderOspfAreaRanges() {
  6657. const tbody = document.getElementById('ospf-ranges-table-body');
  6658. if (!tbody) return;
  6659. const countEl = document.getElementById('ospf-ranges-footer-count');
  6660. const filter = (document.getElementById('filter-ospf-area-ranges')?.value || '').toLowerCase();
  6661. let list = state.ospfAreaRanges || [];
  6662. if (filter) {
  6663. list = list.filter(r => (r.prefix || '').toLowerCase().includes(filter) || (r.area || '').toLowerCase().includes(filter) || (r.comment || '').toLowerCase().includes(filter));
  6664. }
  6665. if (countEl) countEl.innerText = list.length;
  6666. const selId = state.selectedOspfRow?.['area-ranges'];
  6667. tbody.innerHTML = list.map((r, idx) => {
  6668. const isSel = r.id === selId;
  6669. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  6670. const flagD = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  6671. return `
  6672. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('ranges', '${r.id}')" ondblclick="openEditOspfAreaRangeModal('${r.id}')">
  6673. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  6674. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🏷'}</td>
  6675. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(r.comment || '')}</td>
  6676. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(r.area || 'Default')}</td>
  6677. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(r.prefix || '')}</td>
  6678. <td class="py-1.5 px-3">${r.cost || 1}</td>
  6679. <td class="py-1.5 px-3">${r.advertise !== false ? 'yes' : 'no'}</td>
  6680. </tr>
  6681. `;
  6682. }).join('');
  6683. }
  6684. // TAB 4: INTERFACE TEMPLATES
  6685. function renderOspfTemplates() {
  6686. const tbody = document.getElementById('ospf-templates-table-body');
  6687. if (!tbody) return;
  6688. const countEl = document.getElementById('ospf-templates-footer-count');
  6689. const filter = (document.getElementById('filter-ospf-templates')?.value || '').toLowerCase();
  6690. let list = state.ospfTemplates || [];
  6691. if (filter) {
  6692. list = list.filter(t => (t.interfaces || t.interface || '').toLowerCase().includes(filter) || (t.networks || t.network || '').toLowerCase().includes(filter) || (t.comment || '').toLowerCase().includes(filter));
  6693. }
  6694. if (countEl) countEl.innerText = list.length;
  6695. const selId = state.selectedOspfRow?.templates;
  6696. tbody.innerHTML = list.map((t, idx) => {
  6697. const isSel = t.id === selId;
  6698. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  6699. const ifaces = t.interfaces || t.interface || 'all';
  6700. const nets = t.networks || t.network || '';
  6701. const flagD = t.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  6702. return `
  6703. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('templates', '${t.id}')" ondblclick="openEditOspfTemplateModal('${t.id}')">
  6704. <td class="py-1.5 px-3 w-8 text-center text-slate-500 font-bold">${idx}</td>
  6705. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  6706. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(t.comment || '')}</td>
  6707. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  6708. <span class="text-sky-400">↳</span> <span>${escapeHtml(ifaces)}</span>
  6709. </td>
  6710. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(t.area || 'Default')}</td>
  6711. <td class="py-1.5 px-3 font-mono text-sky-300">${escapeHtml(nets)}</td>
  6712. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(t.network_type || 'broadcast')}</td>
  6713. <td class="py-1.5 px-3">${t.cost || 1}</td>
  6714. <td class="py-1.5 px-3">${t.priority || 128}</td>
  6715. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(t.auth || t.auth_type || '')}</td>
  6716. </tr>
  6717. `;
  6718. }).join('');
  6719. }
  6720. // TAB 5: LIVE INTERFACES
  6721. function renderOspfLiveInterfaces() {
  6722. const tbody = document.getElementById('ospf-live-interfaces-table-body');
  6723. if (!tbody) return;
  6724. const countEl = document.getElementById('ospf-live-interfaces-footer-count');
  6725. const filter = (document.getElementById('filter-ospf-interfaces')?.value || '').toLowerCase();
  6726. let list = state.ospfLiveInterfaces || [];
  6727. if (filter) {
  6728. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.address || '').toLowerCase().includes(filter) || (i.state || '').toLowerCase().includes(filter));
  6729. }
  6730. if (countEl) countEl.innerText = list.length;
  6731. tbody.innerHTML = list.map(i => `
  6732. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  6733. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(i.flags || 'D')}</td>
  6734. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(i.interface || '')}</td>
  6735. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(i.address || '')}</td>
  6736. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(i.area || 'Default')}</td>
  6737. <td class="py-1.5 px-3 text-center text-slate-400">${i.instance_id || 0}</td>
  6738. <td class="py-1.5 px-3 font-mono text-amber-300 lowercase">${escapeHtml(i.state || 'waiting')}</td>
  6739. <td class="py-1.5 px-3">${i.cost || 1}</td>
  6740. <td class="py-1.5 px-3">${i.priority || 128}</td>
  6741. </tr>
  6742. `).join('');
  6743. }
  6744. // TAB 6: STATIC NEIGHBORS
  6745. function renderOspfStaticNbrs() {
  6746. const tbody = document.getElementById('ospf-snbrs-table-body');
  6747. if (!tbody) return;
  6748. const countEl = document.getElementById('ospf-snbrs-footer-count');
  6749. const filter = (document.getElementById('filter-ospf-static-nbrs')?.value || '').toLowerCase();
  6750. let list = state.ospfStaticNbrs || [];
  6751. if (filter) {
  6752. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.area || '').toLowerCase().includes(filter) || (n.comment || '').toLowerCase().includes(filter));
  6753. }
  6754. if (countEl) countEl.innerText = list.length;
  6755. const selId = state.selectedOspfRow?.['static-nbrs'];
  6756. tbody.innerHTML = list.map((n, idx) => {
  6757. const isSel = n.id === selId;
  6758. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  6759. const flagD = n.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  6760. return `
  6761. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('snbrs', '${n.id}')" ondblclick="openEditOspfStaticNbrModal('${n.id}')">
  6762. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  6763. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '📡'}</td>
  6764. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  6765. <td class="py-1.5 px-3 font-semibold font-mono text-sky-300">${escapeHtml(n.address || '')}</td>
  6766. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  6767. <td class="py-1.5 px-3">${n.poll_interval || 120}s</td>
  6768. <td class="py-1.5 px-3">${n.cost || 1}</td>
  6769. </tr>
  6770. `;
  6771. }).join('');
  6772. }
  6773. // TAB 7: LIVE NEIGHBORS
  6774. function renderOspfNeighbors() {
  6775. const tbody = document.getElementById('ospf-neighbors-table-body');
  6776. if (!tbody) return;
  6777. const countEl = document.getElementById('ospf-neighbors-footer-count');
  6778. const filter = (document.getElementById('filter-ospf-neighbors')?.value || '').toLowerCase();
  6779. let list = state.ospfNeighbors || [];
  6780. if (filter) {
  6781. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.state || '').toLowerCase().includes(filter) || (n.instance || '').toLowerCase().includes(filter));
  6782. }
  6783. if (countEl) countEl.innerText = list.length;
  6784. tbody.innerHTML = list.map(n => `
  6785. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  6786. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(n.flags || 'D')}</td>
  6787. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  6788. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  6789. <span class="text-sky-400">↳</span> <span>${escapeHtml(n.instance || 'Default')}</span>
  6790. </td>
  6791. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  6792. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(n.address || '')}</td>
  6793. <td class="py-1.5 px-3 font-mono font-bold text-emerald-400">${escapeHtml(n.state || 'Full')}</td>
  6794. <td class="py-1.5 px-3 text-slate-400">${n.state_changes ?? 6}</td>
  6795. </tr>
  6796. `).join('');
  6797. }
  6798. // TAB 8: LINK-STATE DATABASE (LSA)
  6799. function renderOspfLSA() {
  6800. const tbody = document.getElementById('ospf-lsa-table-body');
  6801. if (!tbody) return;
  6802. const countEl = document.getElementById('ospf-lsa-footer-count');
  6803. const filter = (document.getElementById('filter-ospf-lsa')?.value || '').toLowerCase();
  6804. let list = state.ospfLSA || [];
  6805. if (filter) {
  6806. list = list.filter(l => (l.type || '').toLowerCase().includes(filter) || (l.originator || '').toLowerCase().includes(filter) || (l.id || '').toLowerCase().includes(filter));
  6807. }
  6808. if (countEl) countEl.innerText = list.length;
  6809. tbody.innerHTML = list.map(l => `
  6810. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  6811. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(l.flags || 'D')}</td>
  6812. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  6813. <span class="text-sky-400">↳</span> <span>${escapeHtml(l.instance || 'Default')}</span>
  6814. </td>
  6815. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(l.area || 'Default')}</td>
  6816. <td class="py-1.5 px-3 font-mono text-amber-300">${escapeHtml(l.type || 'router')}</td>
  6817. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.originator || '')}</td>
  6818. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(l.id || '')}</td>
  6819. <td class="py-1.5 px-3 text-slate-500">${escapeHtml(l.link || '')}</td>
  6820. <td class="py-1.5 px-3 text-slate-500">${l.link_index ?? 0}</td>
  6821. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.sequence || '')}</td>
  6822. <td class="py-1.5 px-3 text-slate-400">${l.age ?? 0}</td>
  6823. </tr>
  6824. `).join('');
  6825. }
  6826. function renderOspfStatusPill() {
  6827. // Maintained for backward compatibility
  6828. const pill = document.getElementById('ospf-live-status-pill');
  6829. if (!pill) return;
  6830. 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';
  6831. pill.innerText = 'OSPF ACTIVE';
  6832. }
  6833. function renderOspfInterfaces() {
  6834. renderOspfTemplates();
  6835. }
  6836. function renderOspfRoutes() {
  6837. // Routes retained in background
  6838. }
  6839. // BGP Modals & Actions
  6840. function openBgpInstanceModal() {
  6841. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  6842. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  6843. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  6844. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  6845. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  6846. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  6847. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  6848. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  6849. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  6850. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  6851. }
  6852. function closeBgpInstanceModal() {
  6853. document.getElementById('bgp-instance-modal').classList.add('hidden');
  6854. }
  6855. async function submitBgpInstance(e) {
  6856. e.preventDefault();
  6857. const payload = {
  6858. enabled: document.getElementById('modal-bgp-enabled').checked,
  6859. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  6860. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  6861. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  6862. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  6863. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  6864. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  6865. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  6866. };
  6867. try {
  6868. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  6869. method: 'POST',
  6870. headers: { 'Content-Type': 'application/json' },
  6871. body: JSON.stringify(payload)
  6872. });
  6873. if (res.ok) {
  6874. closeBgpInstanceModal();
  6875. showToast('Success', 'BGP instance configuration updated', 'success');
  6876. loadDynamicRouting();
  6877. } else {
  6878. const err = await res.json();
  6879. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  6880. }
  6881. } catch (err) {
  6882. showToast('Error', err.message, 'error');
  6883. }
  6884. }
  6885. // ----------------- BGP Peer Connection Modal (RouterOS v7) -----------------
  6886. function switchBgpPeerModalTab(tab) {
  6887. const tabs = ['general', 'extra', 'attributes', 'filter'];
  6888. tabs.forEach(t => {
  6889. const pane = document.getElementById(`bgp-peer-tab-${t}`);
  6890. const btn = document.getElementById(`bgp-peer-tab-btn-${t}`);
  6891. if (t === tab) {
  6892. if (pane) pane.classList.remove('hidden');
  6893. if (btn) btn.className = 'px-4 py-2 text-xs font-bold border-b-2 border-cyan-500 text-white transition';
  6894. } else {
  6895. if (pane) pane.classList.add('hidden');
  6896. if (btn) btn.className = 'px-4 py-2 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition';
  6897. }
  6898. });
  6899. }
  6900. function addOutputNetworkRow(val = '') {
  6901. const container = document.getElementById('modal-bgp-output-networks-container');
  6902. if (!container) return;
  6903. const row = document.createElement('div');
  6904. row.className = 'flex items-center gap-2 output-net-row';
  6905. row.innerHTML = `
  6906. <input type="text" value="${escapeHtml(val)}" placeholder="e.g. 10.2.51.0/24 or BGP-AWMN" class="flex-1 bg-slate-900 border border-slate-700 rounded-lg px-3 py-1.5 text-white font-mono text-xs focus:outline-none focus:border-cyan-500">
  6907. <button type="button" onclick="this.closest('.output-net-row').remove()" class="w-7 h-7 flex items-center justify-center bg-slate-800 hover:bg-rose-950 text-slate-400 hover:text-rose-400 border border-slate-700 rounded-lg text-base font-bold transition" title="Remove network">-</button>
  6908. `;
  6909. container.appendChild(row);
  6910. }
  6911. function parseBgpTime(val) {
  6912. if (!val) return 0;
  6913. val = String(val).trim();
  6914. if (val.includes(':')) {
  6915. const parts = val.split(':').map(x => parseInt(x, 10) || 0);
  6916. if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2];
  6917. if (parts.length === 2) return parts[0] * 60 + parts[1];
  6918. }
  6919. return parseInt(val, 10) || 0;
  6920. }
  6921. function formatBgpTime(secs) {
  6922. if (!secs || secs <= 0) return '00:00:00';
  6923. const h = Math.floor(secs / 3600);
  6924. const m = Math.floor((secs % 3600) / 60);
  6925. const s = secs % 60;
  6926. return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
  6927. }
  6928. function populateBgpRoutingTables() {
  6929. const sel = document.getElementById('modal-bgp-peer-routing-table');
  6930. if (!sel) return;
  6931. const cur = sel.value || 'main';
  6932. sel.innerHTML = '<option value="main">main</option>';
  6933. (state.routingTables || []).forEach(t => {
  6934. if (t.name !== 'main') {
  6935. const opt = document.createElement('option');
  6936. opt.value = t.name;
  6937. opt.innerText = t.name;
  6938. sel.appendChild(opt);
  6939. }
  6940. });
  6941. sel.value = cur;
  6942. }
  6943. function openAddBgpPeerModal() {
  6944. document.getElementById('bgp-peer-form').reset();
  6945. document.getElementById('modal-bgp-peer-id').value = '';
  6946. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  6947. document.getElementById('modal-bgp-peer-enabled').checked = true;
  6948. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  6949. document.getElementById('modal-bgp-peer-afi-ipv6').checked = false;
  6950. document.getElementById('modal-bgp-peer-connect').checked = true;
  6951. document.getElementById('modal-bgp-peer-listen').checked = true;
  6952. document.getElementById('modal-bgp-peer-holdtime').value = '00:03:00';
  6953. document.getElementById('modal-bgp-peer-keepalive').value = '00:01:00';
  6954. document.getElementById('modal-bgp-peer-nexthop-choice').value = 'force-self';
  6955. document.getElementById('modal-bgp-peer-redist-conn').checked = false;
  6956. document.getElementById('modal-bgp-peer-redist-static').checked = true;
  6957. document.getElementById('modal-bgp-peer-redist-ospf').checked = false;
  6958. document.getElementById('modal-bgp-peer-redist-bgp').checked = false;
  6959. document.getElementById('modal-bgp-peer-default-orig').checked = false;
  6960. populateBgpRoutingTables();
  6961. const container = document.getElementById('modal-bgp-output-networks-container');
  6962. if (container) {
  6963. container.innerHTML = '';
  6964. addOutputNetworkRow('');
  6965. }
  6966. const removeBtn = document.getElementById('modal-btn-remove-peer');
  6967. if (removeBtn) removeBtn.classList.add('hidden');
  6968. switchBgpPeerModalTab('general');
  6969. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  6970. }
  6971. function openEditBgpPeerModal(id) {
  6972. const p = (state.bgpPeers || []).find(item => item.id === id);
  6973. if (!p) return;
  6974. populateBgpRoutingTables();
  6975. document.getElementById('modal-bgp-peer-id').value = p.id;
  6976. document.getElementById('bgp-peer-modal-title').innerText = p.name || p.id;
  6977. // General Tab
  6978. document.getElementById('modal-bgp-peer-enabled').checked = p.enabled !== false && !p.disabled;
  6979. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  6980. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  6981. document.getElementById('modal-bgp-peer-local-as').value = p.local_as || '';
  6982. document.getElementById('modal-bgp-peer-router-id').value = p.router_id || '';
  6983. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  6984. document.getElementById('modal-bgp-peer-afi-ipv6').checked = p.afi === 'ipv6';
  6985. document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  6986. document.getElementById('modal-bgp-peer-remote-port').value = p.remote_port || '';
  6987. document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  6988. document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  6989. document.getElementById('modal-bgp-peer-local-port').value = p.local_port || '';
  6990. document.getElementById('modal-bgp-peer-local-role').value = p.local_role || 'ebgp';
  6991. document.getElementById('modal-bgp-peer-password').value = p.password || '';
  6992. document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  6993. document.getElementById('modal-bgp-peer-connect').checked = p.connect !== false;
  6994. document.getElementById('modal-bgp-peer-listen').checked = p.listen !== false;
  6995. // Extra Tab
  6996. document.getElementById('modal-bgp-peer-holdtime').value = p.hold_time ? formatBgpTime(p.hold_time) : '00:03:00';
  6997. document.getElementById('modal-bgp-peer-keepalive').value = p.keepalive_time ? formatBgpTime(p.keepalive_time) : '00:01:00';
  6998. document.getElementById('modal-bgp-peer-routing-table').value = p.routing_table || 'main';
  6999. document.getElementById('modal-bgp-peer-redist-conn').checked = !!p.redist_connected;
  7000. document.getElementById('modal-bgp-peer-redist-static').checked = p.redist_static !== false;
  7001. document.getElementById('modal-bgp-peer-redist-ospf').checked = !!p.redist_ospf;
  7002. document.getElementById('modal-bgp-peer-redist-bgp').checked = !!p.redist_bgp;
  7003. document.getElementById('modal-bgp-peer-default-orig').checked = !!p.default_originate;
  7004. // Attributes Tab
  7005. document.getElementById('modal-bgp-peer-nexthop-choice').value = p.nexthop_choice || (p.nexthop_self ? 'force-self' : 'default');
  7006. document.getElementById('modal-bgp-peer-default-prepend').value = p.default_prepend || 0;
  7007. document.getElementById('modal-bgp-peer-allow-as-in').value = p.allow_as_in || 0;
  7008. document.getElementById('modal-bgp-peer-remove-priv-as').checked = !!p.remove_private_as;
  7009. document.getElementById('modal-bgp-peer-as-override').checked = !!p.as_override;
  7010. // Filter Tab
  7011. document.getElementById('modal-bgp-peer-in-filter').value = p.in_filter || '';
  7012. document.getElementById('modal-bgp-peer-out-filter').value = p.out_filter || '';
  7013. // Output Networks
  7014. const container = document.getElementById('modal-bgp-output-networks-container');
  7015. if (container) {
  7016. container.innerHTML = '';
  7017. if (p.output_networks && p.output_networks.length > 0) {
  7018. p.output_networks.forEach(net => addOutputNetworkRow(net));
  7019. } else {
  7020. addOutputNetworkRow('');
  7021. }
  7022. }
  7023. const removeBtn = document.getElementById('modal-btn-remove-peer');
  7024. if (removeBtn) removeBtn.classList.remove('hidden');
  7025. switchBgpPeerModalTab('general');
  7026. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  7027. }
  7028. function copyCurrentBgpPeer() {
  7029. document.getElementById('modal-bgp-peer-id').value = '';
  7030. const nameEl = document.getElementById('modal-bgp-peer-name');
  7031. if (nameEl) nameEl.value = (nameEl.value || 'peer') + '-copy';
  7032. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  7033. const removeBtn = document.getElementById('modal-btn-remove-peer');
  7034. if (removeBtn) removeBtn.classList.add('hidden');
  7035. showToast('Cloned', 'BGP connection copied to new draft', 'info');
  7036. }
  7037. function removeCurrentBgpPeer() {
  7038. const id = document.getElementById('modal-bgp-peer-id')?.value;
  7039. if (!id) return;
  7040. deleteBgpPeer(id);
  7041. closeBgpPeerModal();
  7042. }
  7043. function closeBgpPeerModal() {
  7044. document.getElementById('bgp-peer-modal').classList.add('hidden');
  7045. }
  7046. function getBgpPeerFormData() {
  7047. const netInputs = document.querySelectorAll('#modal-bgp-output-networks-container .output-net-row input');
  7048. const outputNetworks = [];
  7049. netInputs.forEach(inp => {
  7050. const v = inp.value.trim();
  7051. if (v) outputNetworks.push(v);
  7052. });
  7053. const enabled = document.getElementById('modal-bgp-peer-enabled').checked;
  7054. return {
  7055. id: document.getElementById('modal-bgp-peer-id').value,
  7056. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  7057. enabled: enabled,
  7058. disabled: !enabled,
  7059. comment: document.getElementById('modal-bgp-peer-comment').value.trim(),
  7060. local_as: parseInt(document.getElementById('modal-bgp-peer-local-as')?.value, 10) || 0,
  7061. router_id: document.getElementById('modal-bgp-peer-router-id').value.trim(),
  7062. afi: document.getElementById('modal-bgp-peer-afi-ipv6').checked ? 'ipv6' : 'ip',
  7063. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  7064. remote_port: parseInt(document.getElementById('modal-bgp-peer-remote-port').value, 10) || 0,
  7065. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10) || 0,
  7066. local_address: document.getElementById('modal-bgp-peer-local-addr').value.trim(),
  7067. local_port: parseInt(document.getElementById('modal-bgp-peer-local-port').value, 10) || 0,
  7068. local_role: document.getElementById('modal-bgp-peer-local-role').value,
  7069. password: document.getElementById('modal-bgp-peer-password').value,
  7070. multihop: document.getElementById('modal-bgp-peer-multihop').checked,
  7071. connect: document.getElementById('modal-bgp-peer-connect').checked,
  7072. listen: document.getElementById('modal-bgp-peer-listen').checked,
  7073. hold_time: parseBgpTime(document.getElementById('modal-bgp-peer-holdtime').value),
  7074. keepalive_time: parseBgpTime(document.getElementById('modal-bgp-peer-keepalive').value),
  7075. routing_table: document.getElementById('modal-bgp-peer-routing-table').value,
  7076. redist_connected: document.getElementById('modal-bgp-peer-redist-conn').checked,
  7077. redist_static: document.getElementById('modal-bgp-peer-redist-static').checked,
  7078. redist_ospf: document.getElementById('modal-bgp-peer-redist-ospf').checked,
  7079. redist_bgp: document.getElementById('modal-bgp-peer-redist-bgp').checked,
  7080. default_originate: document.getElementById('modal-bgp-peer-default-orig').checked,
  7081. nexthop_choice: document.getElementById('modal-bgp-peer-nexthop-choice').value,
  7082. nexthop_self: document.getElementById('modal-bgp-peer-nexthop-choice').value === 'force-self',
  7083. default_prepend: parseInt(document.getElementById('modal-bgp-peer-default-prepend').value, 10) || 0,
  7084. allow_as_in: parseInt(document.getElementById('modal-bgp-peer-allow-as-in').value, 10) || 0,
  7085. remove_private_as: document.getElementById('modal-bgp-peer-remove-priv-as').checked,
  7086. as_override: document.getElementById('modal-bgp-peer-as-override').checked,
  7087. in_filter: (document.getElementById('modal-bgp-peer-in-filter')?.value || '').trim(),
  7088. out_filter: (document.getElementById('modal-bgp-peer-out-filter')?.value || '').trim(),
  7089. output_networks: outputNetworks
  7090. };
  7091. }
  7092. async function submitBgpPeer(e) {
  7093. if (e) e.preventDefault();
  7094. const payload = getBgpPeerFormData();
  7095. try {
  7096. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  7097. method: 'POST',
  7098. headers: { 'Content-Type': 'application/json' },
  7099. body: JSON.stringify(payload)
  7100. });
  7101. if (res.ok) {
  7102. closeBgpPeerModal();
  7103. showToast('Success', 'BGP Connection saved', 'success');
  7104. loadDynamicRouting();
  7105. } else {
  7106. const err = await res.json();
  7107. showToast('Error', err.error || 'Failed to save peer', 'error');
  7108. }
  7109. } catch (err) {
  7110. showToast('Error', err.message, 'error');
  7111. }
  7112. }
  7113. async function applyBgpPeerModal(e) {
  7114. if (e) e.preventDefault();
  7115. const payload = getBgpPeerFormData();
  7116. try {
  7117. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  7118. method: 'POST',
  7119. headers: { 'Content-Type': 'application/json' },
  7120. body: JSON.stringify(payload)
  7121. });
  7122. if (res.ok) {
  7123. const data = await res.json();
  7124. if (data.peer && data.peer.id) {
  7125. document.getElementById('modal-bgp-peer-id').value = data.peer.id;
  7126. document.getElementById('bgp-peer-modal-title').innerText = data.peer.name || data.peer.id;
  7127. document.getElementById('modal-btn-remove-peer')?.classList.remove('hidden');
  7128. }
  7129. showToast('Applied', 'BGP Connection applied', 'success');
  7130. loadDynamicRouting();
  7131. } else {
  7132. const err = await res.json();
  7133. showToast('Error', err.error || 'Failed to apply peer', 'error');
  7134. }
  7135. } catch (err) {
  7136. showToast('Error', err.message, 'error');
  7137. }
  7138. }
  7139. async function deleteBgpPeer(id) {
  7140. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  7141. try {
  7142. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7143. if (res.ok) {
  7144. showToast('Deleted', 'BGP peer removed', 'success');
  7145. loadDynamicRouting();
  7146. }
  7147. } catch (err) {
  7148. showToast('Error', err.message, 'error');
  7149. }
  7150. }
  7151. async function toggleBgpPeerState(id, disabled) {
  7152. try {
  7153. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  7154. method: 'POST',
  7155. headers: { 'Content-Type': 'application/json' },
  7156. body: JSON.stringify({ disabled })
  7157. });
  7158. if (res.ok) {
  7159. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  7160. loadDynamicRouting();
  7161. }
  7162. } catch (err) {
  7163. showToast('Error', err.message, 'error');
  7164. }
  7165. }
  7166. function openAddBgpNetworkModal() {
  7167. document.getElementById('bgp-network-form').reset();
  7168. document.getElementById('modal-bgp-net-id').value = '';
  7169. document.getElementById('bgp-network-modal').classList.remove('hidden');
  7170. }
  7171. function closeBgpNetworkModal() {
  7172. document.getElementById('bgp-network-modal').classList.add('hidden');
  7173. }
  7174. async function submitBgpNetwork(e) {
  7175. e.preventDefault();
  7176. const payload = {
  7177. id: document.getElementById('modal-bgp-net-id').value,
  7178. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  7179. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  7180. disabled: document.getElementById('modal-bgp-net-disabled').checked
  7181. };
  7182. try {
  7183. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  7184. method: 'POST',
  7185. headers: { 'Content-Type': 'application/json' },
  7186. body: JSON.stringify(payload)
  7187. });
  7188. if (res.ok) {
  7189. closeBgpNetworkModal();
  7190. showToast('Success', 'BGP network advertisement saved', 'success');
  7191. loadDynamicRouting();
  7192. } else {
  7193. const err = await res.json();
  7194. showToast('Error', err.error || 'Failed to save network', 'error');
  7195. }
  7196. } catch (err) {
  7197. showToast('Error', err.message, 'error');
  7198. }
  7199. }
  7200. async function deleteBgpNetwork(id) {
  7201. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  7202. try {
  7203. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7204. if (res.ok) {
  7205. showToast('Deleted', 'Network advertisement removed', 'success');
  7206. loadDynamicRouting();
  7207. }
  7208. } catch (err) {
  7209. showToast('Error', err.message, 'error');
  7210. }
  7211. }
  7212. // =========================================================================
  7213. // ROUTEROS v7 OSPF MODALS & ACTIONS
  7214. // =========================================================================
  7215. // --- 1. OSPF INSTANCE ---
  7216. function openOspfInstanceModal(id = null) {
  7217. const isEdit = !!id;
  7218. const inst = (state.ospfInstances || []).find(i => i.id === id) || {
  7219. id: '',
  7220. name: 'Default',
  7221. version: 2,
  7222. vrf: 'main',
  7223. router_id: '192.168.131.56',
  7224. routing_table: 'main',
  7225. enabled: true,
  7226. redistribute_connected: false,
  7227. redistribute_static: true,
  7228. redistribute_bgp: false,
  7229. comment: ''
  7230. };
  7231. document.getElementById('ospf-instance-modal-title').innerText = isEdit ? inst.name : 'New...';
  7232. document.getElementById('modal-ospf-inst-id').value = isEdit ? inst.id : '';
  7233. document.getElementById('modal-ospf-inst-enabled').checked = !inst.disabled;
  7234. document.getElementById('modal-ospf-inst-comment').value = inst.comment || '';
  7235. document.getElementById('modal-ospf-inst-name').value = inst.name || 'Default';
  7236. document.getElementById('modal-ospf-inst-version').value = inst.version || 2;
  7237. document.getElementById('modal-ospf-inst-vrf').value = inst.vrf || 'main';
  7238. document.getElementById('modal-ospf-inst-router-id').value = inst.router_id || '';
  7239. document.getElementById('modal-ospf-inst-routing-table').value = inst.routing_table || 'main';
  7240. document.getElementById('modal-ospf-inst-redist-conn').checked = !!inst.redistribute_connected;
  7241. document.getElementById('modal-ospf-inst-redist-static').checked = inst.redistribute_static !== false;
  7242. document.getElementById('modal-ospf-inst-redist-bgp').checked = !!inst.redistribute_bgp;
  7243. const btnRem = document.getElementById('btn-ospf-inst-modal-remove');
  7244. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  7245. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  7246. }
  7247. function openEditOspfInstanceModal(id) {
  7248. openOspfInstanceModal(id);
  7249. }
  7250. function closeOspfInstanceModal() {
  7251. document.getElementById('ospf-instance-modal').classList.add('hidden');
  7252. }
  7253. async function submitOspfInstance(e) {
  7254. if (e) e.preventDefault();
  7255. const payload = {
  7256. id: document.getElementById('modal-ospf-inst-id').value,
  7257. name: document.getElementById('modal-ospf-inst-name').value.trim() || 'Default',
  7258. version: parseInt(document.getElementById('modal-ospf-inst-version').value, 10) || 2,
  7259. vrf: document.getElementById('modal-ospf-inst-vrf').value.trim() || 'main',
  7260. router_id: document.getElementById('modal-ospf-inst-router-id').value.trim(),
  7261. routing_table: document.getElementById('modal-ospf-inst-routing-table').value.trim() || 'main',
  7262. enabled: document.getElementById('modal-ospf-inst-enabled').checked,
  7263. disabled: !document.getElementById('modal-ospf-inst-enabled').checked,
  7264. comment: document.getElementById('modal-ospf-inst-comment').value.trim(),
  7265. redistribute_connected: document.getElementById('modal-ospf-inst-redist-conn').checked,
  7266. redistribute_static: document.getElementById('modal-ospf-inst-redist-static').checked,
  7267. redistribute_bgp: document.getElementById('modal-ospf-inst-redist-bgp').checked
  7268. };
  7269. try {
  7270. const res = await fetch(`${API_BASE}/routing/ospf/instances`, {
  7271. method: 'POST',
  7272. headers: { 'Content-Type': 'application/json' },
  7273. body: JSON.stringify(payload)
  7274. });
  7275. if (res.ok) {
  7276. closeOspfInstanceModal();
  7277. showToast('Saved', 'OSPF instance updated', 'success');
  7278. loadDynamicRouting();
  7279. } else {
  7280. const err = await res.json();
  7281. showToast('Error', err.error || 'Failed to save OSPF instance', 'error');
  7282. }
  7283. } catch (err) {
  7284. showToast('Error', err.message, 'error');
  7285. }
  7286. }
  7287. function applyOspfInstanceForm() {
  7288. submitOspfInstance(null);
  7289. }
  7290. function copyOspfInstance() {
  7291. document.getElementById('modal-ospf-inst-id').value = '';
  7292. document.getElementById('modal-ospf-inst-name').value += '-copy';
  7293. document.getElementById('ospf-instance-modal-title').innerText = 'New...';
  7294. showToast('Copied', 'Duplicated as new OSPF instance', 'info');
  7295. }
  7296. async function deleteCurrentOspfInstance() {
  7297. const id = document.getElementById('modal-ospf-inst-id').value;
  7298. if (!id) return;
  7299. if (!confirm('Are you sure you want to remove this OSPF instance?')) return;
  7300. try {
  7301. const res = await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7302. if (res.ok) {
  7303. closeOspfInstanceModal();
  7304. showToast('Removed', 'OSPF instance deleted', 'success');
  7305. loadDynamicRouting();
  7306. }
  7307. } catch (err) {
  7308. showToast('Error', err.message, 'error');
  7309. }
  7310. }
  7311. async function enableSelectedOspfInstance() {
  7312. const id = state.selectedOspfRow?.instances;
  7313. if (!id) return;
  7314. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  7315. method: 'POST',
  7316. headers: { 'Content-Type': 'application/json' },
  7317. body: JSON.stringify({ disabled: false })
  7318. });
  7319. loadDynamicRouting();
  7320. }
  7321. async function disableSelectedOspfInstance() {
  7322. const id = state.selectedOspfRow?.instances;
  7323. if (!id) return;
  7324. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  7325. method: 'POST',
  7326. headers: { 'Content-Type': 'application/json' },
  7327. body: JSON.stringify({ disabled: true })
  7328. });
  7329. loadDynamicRouting();
  7330. }
  7331. async function removeSelectedOspfInstance() {
  7332. const id = state.selectedOspfRow?.instances;
  7333. if (!id) return;
  7334. if (!confirm('Delete selected OSPF instance?')) return;
  7335. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7336. loadDynamicRouting();
  7337. }
  7338. async function promptCommentOspfInstance() {
  7339. const id = state.selectedOspfRow?.instances;
  7340. if (!id) return;
  7341. const inst = (state.ospfInstances || []).find(i => i.id === id);
  7342. if (!inst) return;
  7343. const comment = prompt('Enter comment for OSPF instance:', inst.comment || '');
  7344. if (comment === null) return;
  7345. inst.comment = comment;
  7346. await fetch(`${API_BASE}/routing/ospf/instances`, {
  7347. method: 'POST',
  7348. headers: { 'Content-Type': 'application/json' },
  7349. body: JSON.stringify(inst)
  7350. });
  7351. loadDynamicRouting();
  7352. }
  7353. // --- 2. OSPF AREA ---
  7354. function populateOspfAreaDropdowns() {
  7355. const instSelect = document.getElementById('modal-ospf-area-instance');
  7356. if (instSelect) {
  7357. const cur = instSelect.value;
  7358. instSelect.innerHTML = (state.ospfInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  7359. if (instSelect.innerHTML === '') instSelect.innerHTML = '<option value="Default">Default</option>';
  7360. if (cur) instSelect.value = cur;
  7361. }
  7362. }
  7363. function openOspfAreaModal(id = null) {
  7364. const isEdit = !!id;
  7365. populateOspfAreaDropdowns();
  7366. const area = (state.ospfAreas || []).find(a => a.id === id) || {
  7367. id: '',
  7368. name: 'Default',
  7369. instance: 'Default',
  7370. area_id: '0.0.0.0',
  7371. area_type: 'default',
  7372. default_cost: 1,
  7373. no_summaries: false,
  7374. disabled: false,
  7375. comment: ''
  7376. };
  7377. document.getElementById('ospf-area-modal-title').innerText = isEdit ? area.name : 'New...';
  7378. document.getElementById('modal-ospf-area-id').value = isEdit ? area.id : '';
  7379. document.getElementById('modal-ospf-area-enabled').checked = !area.disabled;
  7380. document.getElementById('modal-ospf-area-comment').value = area.comment || '';
  7381. document.getElementById('modal-ospf-area-name').value = area.name || 'Default';
  7382. document.getElementById('modal-ospf-area-instance').value = area.instance || 'Default';
  7383. document.getElementById('modal-ospf-area-areaid').value = area.area_id || '0.0.0.0';
  7384. document.getElementById('modal-ospf-area-type').value = area.area_type || 'default';
  7385. document.getElementById('modal-ospf-area-default-cost').value = area.default_cost || 1;
  7386. document.getElementById('modal-ospf-area-no-summaries').checked = !!area.no_summaries;
  7387. const btnRem = document.getElementById('btn-ospf-area-modal-remove');
  7388. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  7389. document.getElementById('ospf-area-modal').classList.remove('hidden');
  7390. }
  7391. function openEditOspfAreaModal(id) {
  7392. openOspfAreaModal(id);
  7393. }
  7394. function closeOspfAreaModal() {
  7395. document.getElementById('ospf-area-modal').classList.add('hidden');
  7396. }
  7397. async function submitOspfArea(e) {
  7398. if (e) e.preventDefault();
  7399. const payload = {
  7400. id: document.getElementById('modal-ospf-area-id').value,
  7401. name: document.getElementById('modal-ospf-area-name').value.trim() || 'Default',
  7402. instance: document.getElementById('modal-ospf-area-instance').value.trim() || 'Default',
  7403. area_id: document.getElementById('modal-ospf-area-areaid').value.trim() || '0.0.0.0',
  7404. area_type: document.getElementById('modal-ospf-area-type').value,
  7405. default_cost: parseInt(document.getElementById('modal-ospf-area-default-cost').value, 10) || 1,
  7406. no_summaries: document.getElementById('modal-ospf-area-no-summaries').checked,
  7407. disabled: !document.getElementById('modal-ospf-area-enabled').checked,
  7408. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  7409. };
  7410. try {
  7411. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  7412. method: 'POST',
  7413. headers: { 'Content-Type': 'application/json' },
  7414. body: JSON.stringify(payload)
  7415. });
  7416. if (res.ok) {
  7417. closeOspfAreaModal();
  7418. showToast('Saved', 'OSPF area saved', 'success');
  7419. loadDynamicRouting();
  7420. } else {
  7421. const err = await res.json();
  7422. showToast('Error', err.error || 'Failed to save area', 'error');
  7423. }
  7424. } catch (err) {
  7425. showToast('Error', err.message, 'error');
  7426. }
  7427. }
  7428. function applyOspfAreaForm() {
  7429. submitOspfArea(null);
  7430. }
  7431. function copyOspfArea() {
  7432. document.getElementById('modal-ospf-area-id').value = '';
  7433. document.getElementById('modal-ospf-area-name').value += '-copy';
  7434. document.getElementById('ospf-area-modal-title').innerText = 'New...';
  7435. showToast('Copied', 'Duplicated as new OSPF area', 'info');
  7436. }
  7437. async function deleteCurrentOspfArea() {
  7438. const id = document.getElementById('modal-ospf-area-id').value;
  7439. if (!id) return;
  7440. if (!confirm('Are you sure you want to remove this OSPF area?')) return;
  7441. try {
  7442. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7443. if (res.ok) {
  7444. closeOspfAreaModal();
  7445. showToast('Removed', 'OSPF area deleted', 'success');
  7446. loadDynamicRouting();
  7447. }
  7448. } catch (err) {
  7449. showToast('Error', err.message, 'error');
  7450. }
  7451. }
  7452. async function enableSelectedOspfArea() {
  7453. const id = state.selectedOspfRow?.areas;
  7454. if (!id) return;
  7455. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  7456. method: 'POST',
  7457. headers: { 'Content-Type': 'application/json' },
  7458. body: JSON.stringify({ disabled: false })
  7459. });
  7460. loadDynamicRouting();
  7461. }
  7462. async function disableSelectedOspfArea() {
  7463. const id = state.selectedOspfRow?.areas;
  7464. if (!id) return;
  7465. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  7466. method: 'POST',
  7467. headers: { 'Content-Type': 'application/json' },
  7468. body: JSON.stringify({ disabled: true })
  7469. });
  7470. loadDynamicRouting();
  7471. }
  7472. async function removeSelectedOspfArea() {
  7473. const id = state.selectedOspfRow?.areas;
  7474. if (!id) return;
  7475. if (!confirm('Delete selected OSPF area?')) return;
  7476. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7477. loadDynamicRouting();
  7478. }
  7479. async function promptCommentOspfArea() {
  7480. const id = state.selectedOspfRow?.areas;
  7481. if (!id) return;
  7482. const area = (state.ospfAreas || []).find(a => a.id === id);
  7483. if (!area) return;
  7484. const comment = prompt('Enter comment for OSPF area:', area.comment || '');
  7485. if (comment === null) return;
  7486. area.comment = comment;
  7487. await fetch(`${API_BASE}/routing/ospf/areas`, {
  7488. method: 'POST',
  7489. headers: { 'Content-Type': 'application/json' },
  7490. body: JSON.stringify(area)
  7491. });
  7492. loadDynamicRouting();
  7493. }
  7494. // --- 3. OSPF AREA RANGE ---
  7495. function populateAreaRangeDropdowns() {
  7496. const select = document.getElementById('modal-ospf-range-area');
  7497. if (select) {
  7498. const cur = select.value;
  7499. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  7500. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  7501. if (cur) select.value = cur;
  7502. }
  7503. }
  7504. function openOspfAreaRangeModal(id = null) {
  7505. const isEdit = !!id;
  7506. populateAreaRangeDropdowns();
  7507. const r = (state.ospfAreaRanges || []).find(it => it.id === id) || {
  7508. id: '',
  7509. area: 'Default',
  7510. prefix: '',
  7511. cost: 1,
  7512. advertise: true,
  7513. disabled: false,
  7514. comment: ''
  7515. };
  7516. document.getElementById('ospf-area-range-modal-title').innerText = isEdit ? r.prefix : 'New...';
  7517. document.getElementById('modal-ospf-range-id').value = isEdit ? r.id : '';
  7518. document.getElementById('modal-ospf-range-enabled').checked = !r.disabled;
  7519. document.getElementById('modal-ospf-range-comment').value = r.comment || '';
  7520. document.getElementById('modal-ospf-range-area').value = r.area || 'Default';
  7521. document.getElementById('modal-ospf-range-prefix').value = r.prefix || '';
  7522. document.getElementById('modal-ospf-range-cost').value = r.cost || 1;
  7523. document.getElementById('modal-ospf-range-advertise').checked = r.advertise !== false;
  7524. const btnRem = document.getElementById('btn-ospf-range-modal-remove');
  7525. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  7526. document.getElementById('ospf-area-range-modal').classList.remove('hidden');
  7527. }
  7528. function openEditOspfAreaRangeModal(id) {
  7529. openOspfAreaRangeModal(id);
  7530. }
  7531. function closeOspfAreaRangeModal() {
  7532. document.getElementById('ospf-area-range-modal').classList.add('hidden');
  7533. }
  7534. async function submitOspfAreaRange(e) {
  7535. if (e) e.preventDefault();
  7536. const payload = {
  7537. id: document.getElementById('modal-ospf-range-id').value,
  7538. area: document.getElementById('modal-ospf-range-area').value,
  7539. prefix: document.getElementById('modal-ospf-range-prefix').value.trim(),
  7540. cost: parseInt(document.getElementById('modal-ospf-range-cost').value, 10) || 1,
  7541. advertise: document.getElementById('modal-ospf-range-advertise').checked,
  7542. disabled: !document.getElementById('modal-ospf-range-enabled').checked,
  7543. comment: document.getElementById('modal-ospf-range-comment').value.trim()
  7544. };
  7545. try {
  7546. const res = await fetch(`${API_BASE}/routing/ospf/area-ranges`, {
  7547. method: 'POST',
  7548. headers: { 'Content-Type': 'application/json' },
  7549. body: JSON.stringify(payload)
  7550. });
  7551. if (res.ok) {
  7552. closeOspfAreaRangeModal();
  7553. showToast('Saved', 'Area range saved', 'success');
  7554. loadDynamicRouting();
  7555. } else {
  7556. const err = await res.json();
  7557. showToast('Error', err.error || 'Failed to save area range', 'error');
  7558. }
  7559. } catch (err) {
  7560. showToast('Error', err.message, 'error');
  7561. }
  7562. }
  7563. function applyOspfAreaRangeForm() {
  7564. submitOspfAreaRange(null);
  7565. }
  7566. async function deleteCurrentOspfAreaRange() {
  7567. const id = document.getElementById('modal-ospf-range-id').value;
  7568. if (!id) return;
  7569. if (!confirm('Delete this area range?')) return;
  7570. try {
  7571. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7572. closeOspfAreaRangeModal();
  7573. showToast('Removed', 'Area range removed', 'success');
  7574. loadDynamicRouting();
  7575. } catch (err) {
  7576. showToast('Error', err.message, 'error');
  7577. }
  7578. }
  7579. async function enableSelectedOspfAreaRange() {
  7580. const id = state.selectedOspfRow?.['area-ranges'];
  7581. if (!id) return;
  7582. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  7583. if (!r) return;
  7584. r.disabled = false;
  7585. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  7586. loadDynamicRouting();
  7587. }
  7588. async function disableSelectedOspfAreaRange() {
  7589. const id = state.selectedOspfRow?.['area-ranges'];
  7590. if (!id) return;
  7591. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  7592. if (!r) return;
  7593. r.disabled = true;
  7594. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  7595. loadDynamicRouting();
  7596. }
  7597. async function removeSelectedOspfAreaRange() {
  7598. const id = state.selectedOspfRow?.['area-ranges'];
  7599. if (!id) return;
  7600. if (!confirm('Delete selected area range?')) return;
  7601. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7602. loadDynamicRouting();
  7603. }
  7604. async function promptCommentOspfAreaRange() {
  7605. const id = state.selectedOspfRow?.['area-ranges'];
  7606. if (!id) return;
  7607. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  7608. if (!r) return;
  7609. const comment = prompt('Enter comment for area range:', r.comment || '');
  7610. if (comment === null) return;
  7611. r.comment = comment;
  7612. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  7613. loadDynamicRouting();
  7614. }
  7615. // --- 4. OSPF INTERFACE TEMPLATE ---
  7616. function switchOspfTemplateTab(tab) {
  7617. const tabGen = document.getElementById('ospf-tmpl-tab-general');
  7618. const tabAuth = document.getElementById('ospf-tmpl-tab-auth');
  7619. const btnGen = document.getElementById('ospf-tmpl-tab-btn-general');
  7620. const btnAuth = document.getElementById('ospf-tmpl-tab-btn-auth');
  7621. if (tab === 'general') {
  7622. if (tabGen) tabGen.classList.remove('hidden');
  7623. if (tabAuth) tabAuth.classList.add('hidden');
  7624. if (btnGen) btnGen.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  7625. if (btnAuth) btnAuth.className = 'px-4 py-2 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition';
  7626. } else {
  7627. if (tabGen) tabGen.classList.add('hidden');
  7628. if (tabAuth) tabAuth.classList.remove('hidden');
  7629. if (btnGen) btnGen.className = 'px-4 py-2 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition';
  7630. if (btnAuth) btnAuth.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  7631. }
  7632. }
  7633. function populateTemplateAreaDropdowns() {
  7634. const select = document.getElementById('modal-ospf-tmpl-area');
  7635. if (select) {
  7636. const cur = select.value;
  7637. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  7638. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  7639. if (cur) select.value = cur;
  7640. }
  7641. }
  7642. function openOspfTemplateModal(id = null) {
  7643. const isEdit = !!id;
  7644. populateTemplateAreaDropdowns();
  7645. switchOspfTemplateTab('general');
  7646. const tmpl = (state.ospfTemplates || []).find(t => t.id === id) || {
  7647. id: '',
  7648. interfaces: '',
  7649. area: 'Default',
  7650. networks: '',
  7651. network_type: 'broadcast',
  7652. cost: 1,
  7653. priority: 128,
  7654. passive: false,
  7655. hello_interval: 10,
  7656. dead_interval: 40,
  7657. auth: 'none',
  7658. auth_key: '',
  7659. disabled: false,
  7660. comment: ''
  7661. };
  7662. document.getElementById('ospf-template-modal-title').innerText = isEdit ? (tmpl.interfaces || tmpl.networks || 'Template') : 'New...';
  7663. document.getElementById('modal-ospf-tmpl-id').value = isEdit ? tmpl.id : '';
  7664. document.getElementById('modal-ospf-tmpl-enabled').checked = !tmpl.disabled;
  7665. document.getElementById('modal-ospf-tmpl-comment').value = tmpl.comment || '';
  7666. document.getElementById('modal-ospf-tmpl-interfaces').value = tmpl.interfaces || tmpl.interface || '';
  7667. document.getElementById('modal-ospf-tmpl-area').value = tmpl.area || 'Default';
  7668. document.getElementById('modal-ospf-tmpl-networks').value = tmpl.networks || tmpl.network || '';
  7669. document.getElementById('modal-ospf-tmpl-net-type').value = tmpl.network_type || 'broadcast';
  7670. document.getElementById('modal-ospf-tmpl-cost').value = tmpl.cost || 1;
  7671. document.getElementById('modal-ospf-tmpl-priority').value = tmpl.priority || 128;
  7672. document.getElementById('modal-ospf-tmpl-passive').checked = !!tmpl.passive;
  7673. document.getElementById('modal-ospf-tmpl-hello').value = tmpl.hello_interval || 10;
  7674. document.getElementById('modal-ospf-tmpl-dead').value = tmpl.dead_interval || 40;
  7675. document.getElementById('modal-ospf-tmpl-auth').value = tmpl.auth || tmpl.auth_type || 'none';
  7676. document.getElementById('modal-ospf-tmpl-auth-key').value = tmpl.auth_key || '';
  7677. const btnRem = document.getElementById('btn-ospf-tmpl-modal-remove');
  7678. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  7679. document.getElementById('ospf-template-modal').classList.remove('hidden');
  7680. }
  7681. function openEditOspfTemplateModal(id) {
  7682. openOspfTemplateModal(id);
  7683. }
  7684. function closeOspfTemplateModal() {
  7685. document.getElementById('ospf-template-modal').classList.add('hidden');
  7686. }
  7687. async function submitOspfTemplate(e) {
  7688. if (e) e.preventDefault();
  7689. const payload = {
  7690. id: document.getElementById('modal-ospf-tmpl-id').value,
  7691. interfaces: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  7692. interface: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  7693. area: document.getElementById('modal-ospf-tmpl-area').value,
  7694. networks: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  7695. network: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  7696. network_type: document.getElementById('modal-ospf-tmpl-net-type').value,
  7697. cost: parseInt(document.getElementById('modal-ospf-tmpl-cost').value, 10) || 1,
  7698. priority: parseInt(document.getElementById('modal-ospf-tmpl-priority').value, 10) || 128,
  7699. passive: document.getElementById('modal-ospf-tmpl-passive').checked,
  7700. hello_interval: parseInt(document.getElementById('modal-ospf-tmpl-hello').value, 10) || 10,
  7701. dead_interval: parseInt(document.getElementById('modal-ospf-tmpl-dead').value, 10) || 40,
  7702. auth: document.getElementById('modal-ospf-tmpl-auth').value,
  7703. auth_type: document.getElementById('modal-ospf-tmpl-auth').value,
  7704. auth_key: document.getElementById('modal-ospf-tmpl-auth-key').value,
  7705. disabled: !document.getElementById('modal-ospf-tmpl-enabled').checked,
  7706. comment: document.getElementById('modal-ospf-tmpl-comment').value.trim()
  7707. };
  7708. try {
  7709. const res = await fetch(`${API_BASE}/routing/ospf/templates`, {
  7710. method: 'POST',
  7711. headers: { 'Content-Type': 'application/json' },
  7712. body: JSON.stringify(payload)
  7713. });
  7714. if (res.ok) {
  7715. closeOspfTemplateModal();
  7716. showToast('Saved', 'Interface template saved', 'success');
  7717. loadDynamicRouting();
  7718. } else {
  7719. const err = await res.json();
  7720. showToast('Error', err.error || 'Failed to save interface template', 'error');
  7721. }
  7722. } catch (err) {
  7723. showToast('Error', err.message, 'error');
  7724. }
  7725. }
  7726. function applyOspfTemplateForm() {
  7727. submitOspfTemplate(null);
  7728. }
  7729. function copyOspfTemplate() {
  7730. document.getElementById('modal-ospf-tmpl-id').value = '';
  7731. document.getElementById('ospf-template-modal-title').innerText = 'New...';
  7732. showToast('Copied', 'Duplicated as new template', 'info');
  7733. }
  7734. async function deleteCurrentOspfTemplate() {
  7735. const id = document.getElementById('modal-ospf-tmpl-id').value;
  7736. if (!id) return;
  7737. if (!confirm('Delete this interface template?')) return;
  7738. try {
  7739. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7740. closeOspfTemplateModal();
  7741. showToast('Removed', 'Interface template deleted', 'success');
  7742. loadDynamicRouting();
  7743. } catch (err) {
  7744. showToast('Error', err.message, 'error');
  7745. }
  7746. }
  7747. async function enableSelectedOspfTemplate() {
  7748. const id = state.selectedOspfRow?.templates;
  7749. if (!id) return;
  7750. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  7751. method: 'POST',
  7752. headers: { 'Content-Type': 'application/json' },
  7753. body: JSON.stringify({ disabled: false })
  7754. });
  7755. loadDynamicRouting();
  7756. }
  7757. async function disableSelectedOspfTemplate() {
  7758. const id = state.selectedOspfRow?.templates;
  7759. if (!id) return;
  7760. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  7761. method: 'POST',
  7762. headers: { 'Content-Type': 'application/json' },
  7763. body: JSON.stringify({ disabled: true })
  7764. });
  7765. loadDynamicRouting();
  7766. }
  7767. async function removeSelectedOspfTemplate() {
  7768. const id = state.selectedOspfRow?.templates;
  7769. if (!id) return;
  7770. if (!confirm('Delete selected interface template?')) return;
  7771. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7772. loadDynamicRouting();
  7773. }
  7774. async function promptCommentOspfTemplate() {
  7775. const id = state.selectedOspfRow?.templates;
  7776. if (!id) return;
  7777. const tmpl = (state.ospfTemplates || []).find(t => t.id === id);
  7778. if (!tmpl) return;
  7779. const comment = prompt('Enter comment for template:', tmpl.comment || '');
  7780. if (comment === null) return;
  7781. tmpl.comment = comment;
  7782. await fetch(`${API_BASE}/routing/ospf/templates`, {
  7783. method: 'POST',
  7784. headers: { 'Content-Type': 'application/json' },
  7785. body: JSON.stringify(tmpl)
  7786. });
  7787. loadDynamicRouting();
  7788. }
  7789. // --- 5. OSPF STATIC NEIGHBOR ---
  7790. function populateStaticNbrAreaDropdowns() {
  7791. const select = document.getElementById('modal-ospf-snbr-area');
  7792. if (select) {
  7793. const cur = select.value;
  7794. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  7795. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  7796. if (cur) select.value = cur;
  7797. }
  7798. }
  7799. function openOspfStaticNbrModal(id = null) {
  7800. const isEdit = !!id;
  7801. populateStaticNbrAreaDropdowns();
  7802. const nbr = (state.ospfStaticNbrs || []).find(n => n.id === id) || {
  7803. id: '',
  7804. address: '',
  7805. area: 'Default',
  7806. poll_interval: 120,
  7807. cost: 1,
  7808. disabled: false,
  7809. comment: ''
  7810. };
  7811. document.getElementById('ospf-static-nbr-modal-title').innerText = isEdit ? nbr.address : 'New...';
  7812. document.getElementById('modal-ospf-snbr-id').value = isEdit ? nbr.id : '';
  7813. document.getElementById('modal-ospf-snbr-enabled').checked = !nbr.disabled;
  7814. document.getElementById('modal-ospf-snbr-comment').value = nbr.comment || '';
  7815. document.getElementById('modal-ospf-snbr-address').value = nbr.address || '';
  7816. document.getElementById('modal-ospf-snbr-area').value = nbr.area || 'Default';
  7817. document.getElementById('modal-ospf-snbr-poll').value = nbr.poll_interval || 120;
  7818. document.getElementById('modal-ospf-snbr-cost').value = nbr.cost || 1;
  7819. const btnRem = document.getElementById('btn-ospf-snbr-modal-remove');
  7820. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  7821. document.getElementById('ospf-static-nbr-modal').classList.remove('hidden');
  7822. }
  7823. function openEditOspfStaticNbrModal(id) {
  7824. openOspfStaticNbrModal(id);
  7825. }
  7826. function closeOspfStaticNbrModal() {
  7827. document.getElementById('ospf-static-nbr-modal').classList.add('hidden');
  7828. }
  7829. async function submitOspfStaticNbr(e) {
  7830. if (e) e.preventDefault();
  7831. const payload = {
  7832. id: document.getElementById('modal-ospf-snbr-id').value,
  7833. address: document.getElementById('modal-ospf-snbr-address').value.trim(),
  7834. area: document.getElementById('modal-ospf-snbr-area').value,
  7835. poll_interval: parseInt(document.getElementById('modal-ospf-snbr-poll').value, 10) || 120,
  7836. cost: parseInt(document.getElementById('modal-ospf-snbr-cost').value, 10) || 1,
  7837. disabled: !document.getElementById('modal-ospf-snbr-enabled').checked,
  7838. comment: document.getElementById('modal-ospf-snbr-comment').value.trim()
  7839. };
  7840. try {
  7841. const res = await fetch(`${API_BASE}/routing/ospf/static-neighbors`, {
  7842. method: 'POST',
  7843. headers: { 'Content-Type': 'application/json' },
  7844. body: JSON.stringify(payload)
  7845. });
  7846. if (res.ok) {
  7847. closeOspfStaticNbrModal();
  7848. showToast('Saved', 'Static neighbor saved', 'success');
  7849. loadDynamicRouting();
  7850. } else {
  7851. const err = await res.json();
  7852. showToast('Error', err.error || 'Failed to save static neighbor', 'error');
  7853. }
  7854. } catch (err) {
  7855. showToast('Error', err.message, 'error');
  7856. }
  7857. }
  7858. function applyOspfStaticNbrForm() {
  7859. submitOspfStaticNbr(null);
  7860. }
  7861. async function deleteCurrentOspfStaticNbr() {
  7862. const id = document.getElementById('modal-ospf-snbr-id').value;
  7863. if (!id) return;
  7864. if (!confirm('Delete this static neighbor?')) return;
  7865. try {
  7866. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7867. closeOspfStaticNbrModal();
  7868. showToast('Removed', 'Static neighbor removed', 'success');
  7869. loadDynamicRouting();
  7870. } catch (err) {
  7871. showToast('Error', err.message, 'error');
  7872. }
  7873. }
  7874. async function enableSelectedOspfStaticNbr() {
  7875. const id = state.selectedOspfRow?.['static-nbrs'];
  7876. if (!id) return;
  7877. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  7878. if (!n) return;
  7879. n.disabled = false;
  7880. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  7881. loadDynamicRouting();
  7882. }
  7883. async function disableSelectedOspfStaticNbr() {
  7884. const id = state.selectedOspfRow?.['static-nbrs'];
  7885. if (!id) return;
  7886. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  7887. if (!n) return;
  7888. n.disabled = true;
  7889. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  7890. loadDynamicRouting();
  7891. }
  7892. async function removeSelectedOspfStaticNbr() {
  7893. const id = state.selectedOspfRow?.['static-nbrs'];
  7894. if (!id) return;
  7895. if (!confirm('Delete selected static neighbor?')) return;
  7896. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7897. loadDynamicRouting();
  7898. }
  7899. async function promptCommentOspfStaticNbr() {
  7900. const id = state.selectedOspfRow?.['static-nbrs'];
  7901. if (!id) return;
  7902. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  7903. if (!n) return;
  7904. const comment = prompt('Enter comment for static neighbor:', n.comment || '');
  7905. if (comment === null) return;
  7906. n.comment = comment;
  7907. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  7908. loadDynamicRouting();
  7909. }
  7910. // Backward-compat aliases
  7911. function openAddOspfInterfaceModal() { openOspfTemplateModal(); }
  7912. function openEditOspfInterfaceModal(id) { openEditOspfTemplateModal(id); }
  7913. function closeOspfInterfaceModal() { closeOspfTemplateModal(); }
  7914. function submitOspfInterface(e) { submitOspfTemplate(e); }
  7915. function deleteOspfInterface(id) {
  7916. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  7917. }
  7918. function toggleOspfInterfaceState(id, disabled) {
  7919. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  7920. method: 'POST',
  7921. headers: { 'Content-Type': 'application/json' },
  7922. body: JSON.stringify({ disabled })
  7923. }).then(() => loadDynamicRouting());
  7924. }
  7925. function openAddOspfAreaModal() { openOspfAreaModal(); }
  7926. function deleteOspfArea(id) {
  7927. fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  7928. }
  7929. // ============================================================================
  7930. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  7931. // ============================================================================
  7932. function switchBridgeSubTab(tab) {
  7933. state.bridgeSubTab = tab;
  7934. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  7935. tabs.forEach(t => {
  7936. const panel = document.getElementById(`bridge-subtab-${t}`);
  7937. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  7938. if (panel) {
  7939. if (t === tab) panel.classList.remove('hidden');
  7940. else panel.classList.add('hidden');
  7941. }
  7942. if (btn) {
  7943. if (t === tab) {
  7944. 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';
  7945. } else {
  7946. 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';
  7947. }
  7948. }
  7949. });
  7950. const addBtn = document.getElementById('bridge-top-action-btn');
  7951. if (addBtn) {
  7952. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  7953. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  7954. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  7955. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  7956. }
  7957. if (tab === 'hosts') loadBridgeHosts();
  7958. setTimeout(initTableSorting, 50);
  7959. }
  7960. function openCurrentBridgeModal() {
  7961. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  7962. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  7963. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  7964. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  7965. }
  7966. async function loadBridge() {
  7967. try {
  7968. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vlanIfacesRes] = await Promise.all([
  7969. fetch(`${API_BASE}/bridge/bridges`),
  7970. fetch(`${API_BASE}/bridge/ports`),
  7971. fetch(`${API_BASE}/bridge/vlans`),
  7972. fetch(`${API_BASE}/bridge/summary`),
  7973. fetch(`${API_BASE}/vpn/eoip`),
  7974. fetch(`${API_BASE}/vlans`)
  7975. ]);
  7976. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  7977. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  7978. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  7979. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  7980. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  7981. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  7982. // Badges & Stats
  7983. const bBridges = document.getElementById('bridge-badge-bridges');
  7984. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  7985. const bPorts = document.getElementById('bridge-badge-ports');
  7986. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  7987. const bVlans = document.getElementById('bridge-badge-vlans');
  7988. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  7989. const bHosts = document.getElementById('bridge-badge-hosts');
  7990. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  7991. const sBr = document.getElementById('bridge-stat-bridges');
  7992. if (sBr) sBr.innerText = (state.bridges || []).length;
  7993. const sPorts = document.getElementById('bridge-stat-ports');
  7994. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  7995. const sHosts = document.getElementById('bridge-stat-hosts');
  7996. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  7997. renderBridges();
  7998. renderBridgePorts();
  7999. renderBridgeVLANs();
  8000. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  8001. } catch (err) {
  8002. console.error('Failed to load bridge subsystem:', err);
  8003. }
  8004. }
  8005. // ----------------- Bridges -----------------
  8006. function renderBridges() {
  8007. const tbody = document.getElementById('bridge-table-body');
  8008. const empty = document.getElementById('bridge-empty-bridges');
  8009. const countBadge = document.getElementById('bridge-count-badge');
  8010. if (!tbody) return;
  8011. tbody.innerHTML = '';
  8012. const bridges = state.bridges || [];
  8013. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  8014. if (bridges.length === 0) {
  8015. empty?.classList.remove('hidden');
  8016. return;
  8017. }
  8018. empty?.classList.add('hidden');
  8019. bridges.forEach((b, idx) => {
  8020. const tr = document.createElement('tr');
  8021. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  8022. // Format IP addresses pill list
  8023. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  8024. if (b.ip_addresses && b.ip_addresses.length > 0) {
  8025. ipsHtml = b.ip_addresses.map(ip => `
  8026. <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">
  8027. <span>${ip}</span>
  8028. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  8029. </span>
  8030. `).join(' ');
  8031. }
  8032. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  8033. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  8034. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  8035. tr.innerHTML = `
  8036. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  8037. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  8038. <td class="py-2.5 px-3 font-bold text-white text-sm">
  8039. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  8040. </td>
  8041. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  8042. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  8043. <td class="py-2.5 px-3">
  8044. <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>
  8045. </td>
  8046. <td class="py-2.5 px-3 text-center">
  8047. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  8048. </td>
  8049. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  8050. <td class="py-2.5 px-3">
  8051. <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>
  8052. </td>
  8053. <td class="py-2.5 px-3">
  8054. <div class="flex items-center gap-1.5 flex-wrap">
  8055. ${ipsHtml}
  8056. <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>
  8057. </div>
  8058. </td>
  8059. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  8060. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  8061. </td>
  8062. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  8063. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  8064. <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>
  8065. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  8066. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  8067. </td>
  8068. `;
  8069. tbody.appendChild(tr);
  8070. });
  8071. }
  8072. function openAddBridgeModal() {
  8073. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  8074. document.getElementById('bridge-modal-id').value = '';
  8075. document.getElementById('bridge-modal-name').value = 'bridge1';
  8076. document.getElementById('bridge-modal-name').disabled = false;
  8077. document.getElementById('bridge-modal-mtu').value = '1500';
  8078. document.getElementById('bridge-modal-mac').value = '';
  8079. document.getElementById('bridge-modal-stp').value = 'rstp';
  8080. document.getElementById('bridge-modal-priority').value = '32768';
  8081. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  8082. document.getElementById('bridge-modal-pvid').value = '1';
  8083. document.getElementById('bridge-modal-fastforward').checked = true;
  8084. document.getElementById('bridge-modal-comment').value = '';
  8085. document.getElementById('bridge-modal-disabled').checked = false;
  8086. toggleBridgeModalVlanFiltering();
  8087. document.getElementById('bridge-modal').classList.remove('hidden');
  8088. }
  8089. function openEditBridgeModal(id) {
  8090. const b = (state.bridges || []).find(x => x.id === id);
  8091. if (!b) return;
  8092. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  8093. document.getElementById('bridge-modal-id').value = b.id;
  8094. document.getElementById('bridge-modal-name').value = b.name;
  8095. document.getElementById('bridge-modal-name').disabled = true;
  8096. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  8097. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  8098. document.getElementById('bridge-modal-stp').value = b.stp || 'rstp';
  8099. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  8100. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  8101. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  8102. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  8103. document.getElementById('bridge-modal-comment').value = b.comment || '';
  8104. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  8105. toggleBridgeModalVlanFiltering();
  8106. document.getElementById('bridge-modal').classList.remove('hidden');
  8107. }
  8108. function closeBridgeModal() {
  8109. document.getElementById('bridge-modal').classList.add('hidden');
  8110. }
  8111. function toggleBridgeModalVlanFiltering() {
  8112. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  8113. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  8114. if (pvidBox) {
  8115. if (chk) pvidBox.classList.remove('opacity-40');
  8116. else pvidBox.classList.add('opacity-40');
  8117. }
  8118. }
  8119. async function submitSaveBridge(e) {
  8120. e.preventDefault();
  8121. const id = document.getElementById('bridge-modal-id').value;
  8122. const name = document.getElementById('bridge-modal-name').value.trim();
  8123. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  8124. const mac = document.getElementById('bridge-modal-mac').value.trim();
  8125. const stp = document.getElementById('bridge-modal-stp').value;
  8126. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  8127. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  8128. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  8129. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  8130. const comment = document.getElementById('bridge-modal-comment').value.trim();
  8131. const disabled = document.getElementById('bridge-modal-disabled').checked;
  8132. try {
  8133. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  8134. method: 'POST',
  8135. headers: { 'Content-Type': 'application/json' },
  8136. body: JSON.stringify({
  8137. id,
  8138. name,
  8139. mtu,
  8140. mac_address: mac,
  8141. stp,
  8142. priority,
  8143. vlan_filtering: vlanFiltering,
  8144. pvid,
  8145. fast_forward: fastForward,
  8146. comment,
  8147. disabled
  8148. })
  8149. });
  8150. if (res.ok) {
  8151. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  8152. closeBridgeModal();
  8153. loadBridge();
  8154. fetchData(false);
  8155. } else {
  8156. const err = await res.json();
  8157. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  8158. }
  8159. } catch (err) {
  8160. showToast('Error', err.message, 'error');
  8161. }
  8162. }
  8163. async function toggleBridgeState(id, disabled) {
  8164. try {
  8165. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  8166. method: 'POST',
  8167. headers: { 'Content-Type': 'application/json' },
  8168. body: JSON.stringify({ disabled })
  8169. });
  8170. if (res.ok) {
  8171. loadBridge();
  8172. fetchData(false);
  8173. }
  8174. } catch (err) {
  8175. showToast('Error', err.message, 'error');
  8176. }
  8177. }
  8178. async function deleteBridge(id) {
  8179. const b = (state.bridges || []).find(x => x.id === id);
  8180. const name = b ? b.name : id;
  8181. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  8182. try {
  8183. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8184. if (res.ok) {
  8185. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  8186. loadBridge();
  8187. fetchData(false);
  8188. } else {
  8189. const err = await res.json();
  8190. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  8191. }
  8192. } catch (err) {
  8193. showToast('Error', err.message, 'error');
  8194. }
  8195. }
  8196. // ----------------- Bridge IP Assignments -----------------
  8197. function openAddBridgeIPModal(id, name) {
  8198. document.getElementById('bridge-ip-modal-id').value = id;
  8199. document.getElementById('bridge-ip-modal-sub').innerText = name;
  8200. document.getElementById('bridge-ip-modal-cidr').value = '';
  8201. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  8202. }
  8203. function closeBridgeIPModal() {
  8204. document.getElementById('bridge-ip-modal').classList.add('hidden');
  8205. }
  8206. async function submitAddBridgeIP(e) {
  8207. e.preventDefault();
  8208. const id = document.getElementById('bridge-ip-modal-id').value;
  8209. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  8210. try {
  8211. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  8212. method: 'POST',
  8213. headers: { 'Content-Type': 'application/json' },
  8214. body: JSON.stringify({ ip })
  8215. });
  8216. if (res.ok) {
  8217. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  8218. closeBridgeIPModal();
  8219. loadBridge();
  8220. fetchData(false);
  8221. } else {
  8222. const err = await res.json();
  8223. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  8224. }
  8225. } catch (err) {
  8226. showToast('Error', err.message, 'error');
  8227. }
  8228. }
  8229. async function deleteBridgeIP(id, ip) {
  8230. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  8231. try {
  8232. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  8233. method: 'DELETE',
  8234. headers: { 'Content-Type': 'application/json' },
  8235. body: JSON.stringify({ ip })
  8236. });
  8237. if (res.ok) {
  8238. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  8239. loadBridge();
  8240. fetchData(false);
  8241. }
  8242. } catch (err) {
  8243. showToast('Error', err.message, 'error');
  8244. }
  8245. }
  8246. // ----------------- Bridge Ports -----------------
  8247. function renderBridgePorts() {
  8248. const tbody = document.getElementById('bridge-ports-table-body');
  8249. const empty = document.getElementById('bridge-empty-ports');
  8250. const countBadge = document.getElementById('bridge-ports-count-badge');
  8251. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  8252. if (!tbody) return;
  8253. tbody.innerHTML = '';
  8254. // Update filter select
  8255. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  8256. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  8257. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  8258. if (ports.length === 0) {
  8259. empty?.classList.remove('hidden');
  8260. return;
  8261. }
  8262. empty?.classList.add('hidden');
  8263. ports.forEach((p, idx) => {
  8264. const tr = document.createElement('tr');
  8265. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  8266. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  8267. tr.innerHTML = `
  8268. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  8269. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  8270. <td class="py-2.5 px-3 font-bold text-white text-sm">
  8271. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  8272. </td>
  8273. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  8274. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  8275. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  8276. <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>
  8277. <td class="py-2.5 px-3">
  8278. ${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>'}
  8279. </td>
  8280. <td class="py-2.5 px-3">
  8281. <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>
  8282. </td>
  8283. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  8284. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  8285. <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>
  8286. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  8287. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  8288. </td>
  8289. `;
  8290. tbody.appendChild(tr);
  8291. });
  8292. }
  8293. function openAddBridgePortModal() {
  8294. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  8295. document.getElementById('bridge-port-modal-id').value = '';
  8296. populateBridgeSelect('bridge-port-modal-bridge');
  8297. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  8298. document.getElementById('bridge-port-modal-pvid').value = '1';
  8299. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  8300. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  8301. document.getElementById('bridge-port-modal-horizon').value = '0';
  8302. document.getElementById('bridge-port-modal-pathcost').value = '10';
  8303. document.getElementById('bridge-port-modal-priority').value = '128';
  8304. document.getElementById('bridge-port-modal-learn').checked = true;
  8305. document.getElementById('bridge-port-modal-comment').value = '';
  8306. document.getElementById('bridge-port-modal-disabled').checked = false;
  8307. document.getElementById('bridge-port-modal').classList.remove('hidden');
  8308. }
  8309. function openEditBridgePortModal(id) {
  8310. const p = (state.bridgePorts || []).find(x => x.id === id);
  8311. if (!p) return;
  8312. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  8313. document.getElementById('bridge-port-modal-id').value = p.id;
  8314. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  8315. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  8316. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  8317. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  8318. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  8319. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  8320. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  8321. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  8322. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  8323. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  8324. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  8325. document.getElementById('bridge-port-modal').classList.remove('hidden');
  8326. }
  8327. function closeBridgePortModal() {
  8328. document.getElementById('bridge-port-modal').classList.add('hidden');
  8329. }
  8330. async function submitSaveBridgePort(e) {
  8331. e.preventDefault();
  8332. const id = document.getElementById('bridge-port-modal-id').value;
  8333. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  8334. const iface = document.getElementById('bridge-port-modal-interface').value;
  8335. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  8336. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  8337. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  8338. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  8339. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  8340. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  8341. const learn = document.getElementById('bridge-port-modal-learn').checked;
  8342. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  8343. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  8344. try {
  8345. const res = await fetch(`${API_BASE}/bridge/ports`, {
  8346. method: 'POST',
  8347. headers: { 'Content-Type': 'application/json' },
  8348. body: JSON.stringify({
  8349. id,
  8350. bridge,
  8351. interface: iface,
  8352. pvid,
  8353. frame_types: frameTypes,
  8354. ingress_filtering: ingressFiltering,
  8355. horizon,
  8356. path_cost: pathCost,
  8357. priority,
  8358. learn,
  8359. comment,
  8360. disabled
  8361. })
  8362. });
  8363. if (res.ok) {
  8364. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  8365. closeBridgePortModal();
  8366. loadBridge();
  8367. fetchData(false);
  8368. } else {
  8369. const err = await res.json();
  8370. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  8371. }
  8372. } catch (err) {
  8373. showToast('Error', err.message, 'error');
  8374. }
  8375. }
  8376. async function toggleBridgePortState(id, disabled) {
  8377. try {
  8378. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  8379. method: 'POST',
  8380. headers: { 'Content-Type': 'application/json' },
  8381. body: JSON.stringify({ disabled })
  8382. });
  8383. if (res.ok) {
  8384. loadBridge();
  8385. fetchData(false);
  8386. }
  8387. } catch (err) {
  8388. showToast('Error', err.message, 'error');
  8389. }
  8390. }
  8391. async function deleteBridgePort(id) {
  8392. const p = (state.bridgePorts || []).find(x => x.id === id);
  8393. const iface = p ? p.interface : id;
  8394. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  8395. try {
  8396. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8397. if (res.ok) {
  8398. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  8399. loadBridge();
  8400. fetchData(false);
  8401. }
  8402. } catch (err) {
  8403. showToast('Error', err.message, 'error');
  8404. }
  8405. }
  8406. // ----------------- Bridge VLANs -----------------
  8407. function renderBridgeVLANs() {
  8408. const tbody = document.getElementById('bridge-vlans-table-body');
  8409. const empty = document.getElementById('bridge-empty-vlans');
  8410. const countBadge = document.getElementById('bridge-vlans-count-badge');
  8411. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  8412. if (!tbody) return;
  8413. tbody.innerHTML = '';
  8414. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  8415. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  8416. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  8417. if (vlans.length === 0) {
  8418. empty?.classList.remove('hidden');
  8419. return;
  8420. }
  8421. empty?.classList.add('hidden');
  8422. vlans.forEach((v, idx) => {
  8423. const tr = document.createElement('tr');
  8424. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  8425. const taggedHtml = (v.tagged && v.tagged.length > 0)
  8426. ? 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(' ')
  8427. : '<span class="text-slate-600">none</span>';
  8428. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  8429. ? 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(' ')
  8430. : '<span class="text-slate-600">none</span>';
  8431. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  8432. tr.innerHTML = `
  8433. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  8434. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  8435. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  8436. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  8437. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  8438. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  8439. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  8440. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  8441. <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>
  8442. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  8443. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  8444. </td>
  8445. `;
  8446. tbody.appendChild(tr);
  8447. });
  8448. }
  8449. function openAddBridgeVLANModal() {
  8450. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  8451. document.getElementById('bridge-vlan-modal-id').value = '';
  8452. populateBridgeSelect('bridge-vlan-modal-bridge');
  8453. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  8454. document.getElementById('bridge-vlan-modal-comment').value = '';
  8455. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  8456. updateBridgeVlanPortCheckboxes();
  8457. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  8458. }
  8459. function openEditBridgeVLANModal(id) {
  8460. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  8461. if (!v) return;
  8462. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  8463. document.getElementById('bridge-vlan-modal-id').value = v.id;
  8464. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  8465. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  8466. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  8467. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  8468. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  8469. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  8470. }
  8471. function closeBridgeVlanModal() {
  8472. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  8473. }
  8474. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  8475. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  8476. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  8477. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  8478. if (!taggedBox || !untaggedBox) return;
  8479. // Ports belonging to the selected bridge
  8480. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  8481. if (memberPorts.length === 0) {
  8482. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  8483. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  8484. return;
  8485. }
  8486. taggedBox.innerHTML = memberPorts.map(p => `
  8487. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  8488. <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">
  8489. <span>${p.interface}</span>
  8490. </label>
  8491. `).join('');
  8492. untaggedBox.innerHTML = memberPorts.map(p => `
  8493. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  8494. <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">
  8495. <span>${p.interface}</span>
  8496. </label>
  8497. `).join('');
  8498. }
  8499. async function submitSaveBridgeVLAN(e) {
  8500. e.preventDefault();
  8501. const id = document.getElementById('bridge-vlan-modal-id').value;
  8502. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  8503. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  8504. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  8505. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  8506. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  8507. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  8508. try {
  8509. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  8510. method: 'POST',
  8511. headers: { 'Content-Type': 'application/json' },
  8512. body: JSON.stringify({
  8513. id,
  8514. bridge,
  8515. vlan_ids: vlanIDs,
  8516. tagged,
  8517. untagged,
  8518. comment,
  8519. disabled
  8520. })
  8521. });
  8522. if (res.ok) {
  8523. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  8524. closeBridgeVlanModal();
  8525. loadBridge();
  8526. } else {
  8527. const err = await res.json();
  8528. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  8529. }
  8530. } catch (err) {
  8531. showToast('Error', err.message, 'error');
  8532. }
  8533. }
  8534. async function toggleBridgeVLANState(id, disabled) {
  8535. try {
  8536. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  8537. method: 'POST',
  8538. headers: { 'Content-Type': 'application/json' },
  8539. body: JSON.stringify({ disabled })
  8540. });
  8541. if (res.ok) loadBridge();
  8542. } catch (err) {
  8543. showToast('Error', err.message, 'error');
  8544. }
  8545. }
  8546. async function deleteBridgeVLAN(id) {
  8547. if (!confirm('Delete this bridge VLAN entry?')) return;
  8548. try {
  8549. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8550. if (res.ok) {
  8551. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  8552. loadBridge();
  8553. }
  8554. } catch (err) {
  8555. showToast('Error', err.message, 'error');
  8556. }
  8557. }
  8558. // ----------------- Hosts / MAC Table -----------------
  8559. async function loadBridgeHosts() {
  8560. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  8561. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  8562. try {
  8563. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  8564. const res = await fetch(url);
  8565. if (res.ok) {
  8566. state.bridgeHosts = await res.json();
  8567. renderBridgeHosts();
  8568. }
  8569. } catch (err) {
  8570. console.error('Failed to load bridge hosts:', err);
  8571. }
  8572. }
  8573. function renderBridgeHosts() {
  8574. const tbody = document.getElementById('bridge-hosts-table-body');
  8575. const empty = document.getElementById('bridge-empty-hosts');
  8576. const countBadge = document.getElementById('bridge-hosts-count-badge');
  8577. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  8578. if (!tbody) return;
  8579. tbody.innerHTML = '';
  8580. const hosts = (state.bridgeHosts || []).filter(h => {
  8581. if (!search) return true;
  8582. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  8583. });
  8584. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  8585. if (hosts.length === 0) {
  8586. empty?.classList.remove('hidden');
  8587. return;
  8588. }
  8589. empty?.classList.add('hidden');
  8590. hosts.forEach(h => {
  8591. const tr = document.createElement('tr');
  8592. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  8593. let flagBadges = '';
  8594. 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>';
  8595. 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>';
  8596. 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>';
  8597. tr.innerHTML = `
  8598. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  8599. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  8600. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  8601. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  8602. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  8603. <td class="py-2.5 px-3">${flagBadges}</td>
  8604. `;
  8605. tbody.appendChild(tr);
  8606. });
  8607. }
  8608. async function flushBridgeHosts() {
  8609. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  8610. if (!selBridge) {
  8611. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  8612. return;
  8613. }
  8614. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  8615. try {
  8616. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  8617. method: 'POST',
  8618. headers: { 'Content-Type': 'application/json' },
  8619. body: JSON.stringify({ bridge: selBridge })
  8620. });
  8621. if (res.ok) {
  8622. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  8623. loadBridgeHosts();
  8624. }
  8625. } catch (err) {
  8626. showToast('Error', err.message, 'error');
  8627. }
  8628. }
  8629. // ----------------- Helpers -----------------
  8630. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  8631. const sel = document.getElementById(selectId);
  8632. if (!sel) return;
  8633. const prevVal = currentVal || sel.value;
  8634. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  8635. (state.bridges || []).forEach(b => {
  8636. const opt = document.createElement('option');
  8637. opt.value = b.name;
  8638. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  8639. if (b.name === prevVal) opt.selected = true;
  8640. sel.appendChild(opt);
  8641. });
  8642. }
  8643. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  8644. const sel = document.getElementById(selectId);
  8645. if (!sel) return;
  8646. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  8647. // 1. Physical Interfaces
  8648. const grpPhys = document.createElement('optgroup');
  8649. grpPhys.label = 'Physical Interfaces';
  8650. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  8651. const opt = document.createElement('option');
  8652. opt.value = i.name;
  8653. opt.innerText = `${i.name} (${i.role || i.type})`;
  8654. if (i.name === currentVal) opt.selected = true;
  8655. grpPhys.appendChild(opt);
  8656. });
  8657. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  8658. // 2. VLAN Sub-interfaces
  8659. const grpVlans = document.createElement('optgroup');
  8660. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  8661. (state.vlans || []).forEach(v => {
  8662. const opt = document.createElement('option');
  8663. opt.value = v.name;
  8664. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  8665. if (v.name === currentVal) opt.selected = true;
  8666. grpVlans.appendChild(opt);
  8667. });
  8668. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  8669. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  8670. const grpEoip = document.createElement('optgroup');
  8671. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  8672. (state.eoipTunnels || []).forEach(t => {
  8673. const opt = document.createElement('option');
  8674. opt.value = t.name;
  8675. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  8676. if (t.name === currentVal) opt.selected = true;
  8677. grpEoip.appendChild(opt);
  8678. });
  8679. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  8680. }
  8681. // -------------------------------------------------------------
  8682. // Routing Filters Management (/routing filter)
  8683. // -------------------------------------------------------------
  8684. function renderRoutingFilters() {
  8685. const tbody = document.getElementById('routing-filters-table-body');
  8686. if (!tbody) return;
  8687. const empty = document.getElementById('routing-filters-empty');
  8688. const countBadge = document.getElementById('routing-filters-count-badge');
  8689. const navBadge = document.getElementById('badge-filters-count');
  8690. const chainSelect = document.getElementById('routing-filter-chain-select');
  8691. const allRules = state.routingFilters || [];
  8692. if (navBadge) navBadge.innerText = allRules.length;
  8693. // Populate chain filter select options dynamically
  8694. if (chainSelect) {
  8695. const currentVal = state.filterChainSelected || 'all';
  8696. const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
  8697. chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
  8698. uniqueChains.map(ch => {
  8699. const count = allRules.filter(r => r.chain === ch).length;
  8700. return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
  8701. }).join('');
  8702. chainSelect.value = currentVal;
  8703. }
  8704. // Filter rules by selected chain
  8705. const filteredRules = (state.filterChainSelected && state.filterChainSelected !== 'all')
  8706. ? allRules.filter(r => r.chain === state.filterChainSelected)
  8707. : allRules.slice();
  8708. // Sort by chain then rule_order
  8709. filteredRules.sort((a, b) => {
  8710. if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
  8711. return (a.rule_order || 0) - (b.rule_order || 0);
  8712. });
  8713. if (countBadge) countBadge.innerText = `${filteredRules.length} Rules`;
  8714. if (filteredRules.length === 0) {
  8715. tbody.innerHTML = '';
  8716. if (empty) empty.classList.remove('hidden');
  8717. return;
  8718. }
  8719. if (empty) empty.classList.add('hidden');
  8720. tbody.innerHTML = filteredRules.map(r => {
  8721. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  8722. const flagX = r.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  8723. let actionBadge = '';
  8724. if (r.action === 'accept') {
  8725. 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>';
  8726. } else if (r.action === 'discard') {
  8727. 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>';
  8728. } else if (r.action === 'reject') {
  8729. 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>';
  8730. } else {
  8731. 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>`;
  8732. }
  8733. // Prefix match
  8734. let matchPfx = '';
  8735. if (r.prefix) {
  8736. matchPfx = `<span class="font-bold text-white">${escapeHtml(r.prefix)}</span>`;
  8737. if (r.prefix_len) {
  8738. matchPfx += ` <span class="text-slate-400 text-[11px] font-normal">[${escapeHtml(r.prefix_len)}]</span>`;
  8739. }
  8740. } else {
  8741. matchPfx = '<span class="text-slate-500 italic">any prefix</span>';
  8742. }
  8743. // Other matches
  8744. const matchExtra = [];
  8745. if (r.match_protocol && r.match_protocol !== 'any') {
  8746. 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>`);
  8747. }
  8748. if (r.match_as_path) {
  8749. 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>`);
  8750. }
  8751. if (r.match_community) {
  8752. 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>`);
  8753. }
  8754. const matchExtraHtml = matchExtra.length > 0 ? matchExtra.join(' ') : '<span class="text-slate-600">-</span>';
  8755. // Set modifications
  8756. const setBadges = [];
  8757. if (r.set_local_pref > 0) {
  8758. 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>`);
  8759. }
  8760. if (r.set_metric > 0) {
  8761. 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>`);
  8762. }
  8763. if (r.set_as_prepend > 0) {
  8764. 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>`);
  8765. }
  8766. if (r.set_community) {
  8767. 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>`);
  8768. }
  8769. if (r.set_next_hop) {
  8770. 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>`);
  8771. }
  8772. const setHtml = setBadges.length > 0 ? setBadges.join(' ') : '<span class="text-slate-600">-</span>';
  8773. return `
  8774. <tr class="hover:bg-slate-800/40 transition">
  8775. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagX}</td>
  8776. <td class="py-2.5 px-3 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  8777. <td class="py-2.5 px-3">
  8778. <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>
  8779. </td>
  8780. <td class="py-2.5 px-3">${actionBadge}</td>
  8781. <td class="py-2.5 px-3 font-mono">${matchPfx}</td>
  8782. <td class="py-2.5 px-3 space-x-1">${matchExtraHtml}</td>
  8783. <td class="py-2.5 px-3 space-x-1 font-mono">${setHtml}</td>
  8784. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  8785. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  8786. <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'}">
  8787. ${r.disabled ? 'Enable' : 'Disable'}
  8788. </button>
  8789. <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">
  8790. Edit
  8791. </button>
  8792. <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">
  8793. Delete
  8794. </button>
  8795. </td>
  8796. </tr>
  8797. `;
  8798. }).join('');
  8799. }
  8800. function filterRoutingFiltersByChain(chain) {
  8801. state.filterChainSelected = chain;
  8802. renderRoutingFilters();
  8803. }
  8804. function openAddRoutingFilterModal(defaultChain = '') {
  8805. const form = document.getElementById('routing-filter-form');
  8806. if (form) form.reset();
  8807. const idEl = document.getElementById('modal-rf-id');
  8808. if (idEl) idEl.value = '';
  8809. const titleEl = document.getElementById('modal-rf-title');
  8810. if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
  8811. const chainEl = document.getElementById('modal-rf-chain');
  8812. if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
  8813. const orderEl = document.getElementById('modal-rf-order');
  8814. if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
  8815. const actEl = document.getElementById('modal-rf-action');
  8816. if (actEl) actEl.value = 'accept';
  8817. const protoEl = document.getElementById('modal-rf-protocol');
  8818. if (protoEl) protoEl.value = 'any';
  8819. const disEl = document.getElementById('modal-rf-disabled');
  8820. if (disEl) disEl.checked = false;
  8821. const modal = document.getElementById('modal-routing-filter');
  8822. if (modal) modal.classList.remove('hidden');
  8823. }
  8824. function openEditRoutingFilterModal(id) {
  8825. const r = (state.routingFilters || []).find(item => item.id === id);
  8826. if (!r) return;
  8827. const idEl = document.getElementById('modal-rf-id');
  8828. if (idEl) idEl.value = r.id;
  8829. const titleEl = document.getElementById('modal-rf-title');
  8830. if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
  8831. const chainEl = document.getElementById('modal-rf-chain');
  8832. if (chainEl) chainEl.value = r.chain || '';
  8833. const orderEl = document.getElementById('modal-rf-order');
  8834. if (orderEl) orderEl.value = r.rule_order || 10;
  8835. const actEl = document.getElementById('modal-rf-action');
  8836. if (actEl) actEl.value = r.action || 'accept';
  8837. const pfxEl = document.getElementById('modal-rf-prefix');
  8838. if (pfxEl) pfxEl.value = r.prefix || '';
  8839. const pfxLenEl = document.getElementById('modal-rf-prefix-len');
  8840. if (pfxLenEl) pfxLenEl.value = r.prefix_len || '';
  8841. const protoEl = document.getElementById('modal-rf-protocol');
  8842. if (protoEl) protoEl.value = r.match_protocol || 'any';
  8843. const aspEl = document.getElementById('modal-rf-as-path');
  8844. if (aspEl) aspEl.value = r.match_as_path || '';
  8845. const commEl = document.getElementById('modal-rf-community');
  8846. if (commEl) commEl.value = r.match_community || '';
  8847. const lpEl = document.getElementById('modal-rf-set-local-pref');
  8848. if (lpEl) lpEl.value = r.set_local_pref || '';
  8849. const metEl = document.getElementById('modal-rf-set-metric');
  8850. if (metEl) metEl.value = r.set_metric || '';
  8851. const prepEl = document.getElementById('modal-rf-set-as-prepend');
  8852. if (prepEl) prepEl.value = r.set_as_prepend || '';
  8853. const setCommEl = document.getElementById('modal-rf-set-community');
  8854. if (setCommEl) setCommEl.value = r.set_community || '';
  8855. const nhEl = document.getElementById('modal-rf-set-next-hop');
  8856. if (nhEl) nhEl.value = r.set_next_hop || '';
  8857. const comEl = document.getElementById('modal-rf-comment');
  8858. if (comEl) comEl.value = r.comment || '';
  8859. const disEl = document.getElementById('modal-rf-disabled');
  8860. if (disEl) disEl.checked = !!r.disabled;
  8861. const modal = document.getElementById('modal-routing-filter');
  8862. if (modal) modal.classList.remove('hidden');
  8863. }
  8864. function closeRoutingFilterModal() {
  8865. const modal = document.getElementById('modal-routing-filter');
  8866. if (modal) modal.classList.add('hidden');
  8867. }
  8868. async function submitRoutingFilter(e) {
  8869. e.preventDefault();
  8870. const payload = {
  8871. id: document.getElementById('modal-rf-id').value,
  8872. chain: document.getElementById('modal-rf-chain').value.trim(),
  8873. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  8874. action: document.getElementById('modal-rf-action').value,
  8875. prefix: document.getElementById('modal-rf-prefix').value.trim(),
  8876. prefix_len: document.getElementById('modal-rf-prefix-len').value.trim(),
  8877. match_protocol: document.getElementById('modal-rf-protocol').value,
  8878. match_as_path: document.getElementById('modal-rf-as-path').value.trim(),
  8879. match_community: document.getElementById('modal-rf-community').value.trim(),
  8880. set_local_pref: parseInt(document.getElementById('modal-rf-set-local-pref').value, 10) || 0,
  8881. set_metric: parseInt(document.getElementById('modal-rf-set-metric').value, 10) || 0,
  8882. set_as_prepend: parseInt(document.getElementById('modal-rf-set-as-prepend').value, 10) || 0,
  8883. set_community: document.getElementById('modal-rf-set-community').value.trim(),
  8884. set_next_hop: document.getElementById('modal-rf-set-next-hop').value.trim(),
  8885. comment: document.getElementById('modal-rf-comment').value.trim(),
  8886. disabled: document.getElementById('modal-rf-disabled').checked
  8887. };
  8888. try {
  8889. const res = await fetch(`${API_BASE}/routing/filters`, {
  8890. method: 'POST',
  8891. headers: { 'Content-Type': 'application/json' },
  8892. body: JSON.stringify(payload)
  8893. });
  8894. if (res.ok) {
  8895. closeRoutingFilterModal();
  8896. showToast('Success', 'Routing filter rule saved', 'success');
  8897. loadDynamicRouting();
  8898. } else {
  8899. const err = await res.json();
  8900. showToast('Error', err.error || 'Failed to save filter rule', 'error');
  8901. }
  8902. } catch (err) {
  8903. showToast('Error', err.message, 'error');
  8904. }
  8905. }
  8906. async function deleteRoutingFilter(id) {
  8907. if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
  8908. try {
  8909. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8910. if (res.ok) {
  8911. showToast('Deleted', 'Routing filter rule removed', 'info');
  8912. loadDynamicRouting();
  8913. } else {
  8914. const err = await res.json();
  8915. showToast('Error', err.error || 'Failed to delete rule', 'error');
  8916. }
  8917. } catch (err) {
  8918. showToast('Error', err.message, 'error');
  8919. }
  8920. }
  8921. async function toggleRoutingFilterState(id, disabled) {
  8922. try {
  8923. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
  8924. method: 'POST',
  8925. headers: { 'Content-Type': 'application/json' },
  8926. body: JSON.stringify({ disabled })
  8927. });
  8928. if (res.ok) {
  8929. showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  8930. loadDynamicRouting();
  8931. } else {
  8932. const err = await res.json();
  8933. showToast('Error', err.error || 'Failed to toggle rule state', 'error');
  8934. }
  8935. } catch (err) {
  8936. showToast('Error', err.message, 'error');
  8937. }
  8938. }
  8939. // ==========================================
  8940. // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
  8941. // ==========================================
  8942. function loadToolsView() {
  8943. populateToolsInterfaces();
  8944. switchToolsSubTab(state.activeToolsSubTab || 'ping');
  8945. }
  8946. function populateToolsInterfaces() {
  8947. const pingSel = document.getElementById('tools-ping-iface');
  8948. const traceSel = document.getElementById('tools-tr-iface');
  8949. let opts = '<option value="">Auto (Default Route)</option>';
  8950. if (Array.isArray(state.interfaces)) {
  8951. state.interfaces.forEach(iface => {
  8952. if (iface.name) {
  8953. opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
  8954. }
  8955. });
  8956. }
  8957. if (pingSel) {
  8958. const cur = pingSel.value;
  8959. pingSel.innerHTML = opts;
  8960. if (cur) pingSel.value = cur;
  8961. }
  8962. if (traceSel) {
  8963. const cur = traceSel.value;
  8964. traceSel.innerHTML = opts;
  8965. if (cur) traceSel.value = cur;
  8966. }
  8967. }
  8968. function switchToolsSubTab(subTab) {
  8969. state.activeToolsSubTab = subTab;
  8970. const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
  8971. tabs.forEach(t => {
  8972. const btn = document.getElementById(`tools-subtab-btn-${t}`);
  8973. const view = document.getElementById(`tools-view-${t}`);
  8974. if (btn) {
  8975. if (t === subTab) {
  8976. 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';
  8977. } else {
  8978. 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';
  8979. }
  8980. }
  8981. if (view) {
  8982. if (t === subTab) {
  8983. view.classList.remove('hidden');
  8984. } else {
  8985. view.classList.add('hidden');
  8986. }
  8987. }
  8988. });
  8989. }
  8990. function setPortPreset(port) {
  8991. const input = document.getElementById('tools-port-num');
  8992. if (input) input.value = port;
  8993. }
  8994. let pingAbortController = null;
  8995. let tracerouteAbortController = null;
  8996. function clearPingTable() {
  8997. const tbody = document.getElementById('tools-ping-tbody');
  8998. if (tbody) tbody.innerHTML = '';
  8999. const rawEl = document.getElementById('tools-ping-raw');
  9000. if (rawEl) rawEl.innerText = '';
  9001. const sentEl = document.getElementById('tools-ping-stat-sent');
  9002. if (sentEl) sentEl.innerText = '0';
  9003. const recvEl = document.getElementById('tools-ping-stat-recv');
  9004. if (recvEl) recvEl.innerText = '0';
  9005. const lossEl = document.getElementById('tools-ping-stat-loss');
  9006. if (lossEl) lossEl.innerText = '0%';
  9007. const avgEl = document.getElementById('tools-ping-stat-avg');
  9008. if (avgEl) avgEl.innerText = '0 ms';
  9009. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  9010. if (minMaxEl) minMaxEl.innerText = '-';
  9011. const badge = document.getElementById('tools-ping-status-badge');
  9012. if (badge) {
  9013. badge.className = '';
  9014. badge.innerText = '';
  9015. }
  9016. }
  9017. function clearTracerouteTable() {
  9018. const tbody = document.getElementById('tools-tr-tbody');
  9019. if (tbody) tbody.innerHTML = '';
  9020. const rawEl = document.getElementById('tools-tr-raw');
  9021. if (rawEl) rawEl.innerText = '';
  9022. const statHops = document.getElementById('tools-tr-hops-count');
  9023. if (statHops) statHops.innerText = '0 Hops';
  9024. }
  9025. function resetPingButton() {
  9026. const btn = document.getElementById('tools-ping-btn');
  9027. const btnText = document.getElementById('tools-ping-btn-text');
  9028. const spinner = document.getElementById('tools-ping-spinner');
  9029. if (btn) {
  9030. btn.disabled = false;
  9031. 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';
  9032. }
  9033. if (btnText) btnText.innerText = 'Start Ping';
  9034. if (spinner) spinner.classList.add('hidden');
  9035. }
  9036. function setPingRunningButton() {
  9037. const btn = document.getElementById('tools-ping-btn');
  9038. const btnText = document.getElementById('tools-ping-btn-text');
  9039. const spinner = document.getElementById('tools-ping-spinner');
  9040. if (btn) {
  9041. btn.disabled = false;
  9042. 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';
  9043. }
  9044. if (btnText) btnText.innerText = 'Stop Ping';
  9045. if (spinner) spinner.classList.remove('hidden');
  9046. }
  9047. function resetTracerouteButton() {
  9048. const btn = document.getElementById('tools-tr-btn');
  9049. const btnText = document.getElementById('tools-tr-btn-text');
  9050. const spinner = document.getElementById('tools-tr-spinner');
  9051. if (btn) {
  9052. btn.disabled = false;
  9053. 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';
  9054. }
  9055. if (btnText) btnText.innerText = 'Start Traceroute';
  9056. if (spinner) spinner.classList.add('hidden');
  9057. }
  9058. function setTracerouteRunningButton() {
  9059. const btn = document.getElementById('tools-tr-btn');
  9060. const btnText = document.getElementById('tools-tr-btn-text');
  9061. const spinner = document.getElementById('tools-tr-spinner');
  9062. if (btn) {
  9063. btn.disabled = false;
  9064. 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';
  9065. }
  9066. if (btnText) btnText.innerText = 'Stop Traceroute';
  9067. if (spinner) spinner.classList.remove('hidden');
  9068. }
  9069. async function executePing(e) {
  9070. if (e) e.preventDefault();
  9071. // If already running, clicking the button stops the stream!
  9072. if (pingAbortController) {
  9073. pingAbortController.abort();
  9074. pingAbortController = null;
  9075. resetPingButton();
  9076. showToast('Ping Stopped', 'Live ping stopped by user', 'info');
  9077. return;
  9078. }
  9079. const target = document.getElementById('tools-ping-target')?.value?.trim();
  9080. const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
  9081. const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
  9082. const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '3', 10);
  9083. const iface = document.getElementById('tools-ping-iface')?.value || '';
  9084. const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
  9085. if (!target) {
  9086. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  9087. return;
  9088. }
  9089. clearPingTable();
  9090. const resCard = document.getElementById('tools-ping-results');
  9091. if (resCard) resCard.classList.remove('hidden');
  9092. pingAbortController = new AbortController();
  9093. setPingRunningButton();
  9094. try {
  9095. const res = await fetch(`${API_BASE}/tools/ping/stream`, {
  9096. method: 'POST',
  9097. headers: { 'Content-Type': 'application/json' },
  9098. body: JSON.stringify({
  9099. target,
  9100. count,
  9101. size,
  9102. timeout,
  9103. interface: iface,
  9104. dont_frag: dontFrag
  9105. }),
  9106. signal: pingAbortController.signal
  9107. });
  9108. if (!res.ok) {
  9109. const errText = await res.text();
  9110. showToast('Ping Error', errText || 'Failed to start live ping', 'error');
  9111. resetPingButton();
  9112. pingAbortController = null;
  9113. return;
  9114. }
  9115. const reader = res.body.getReader();
  9116. const decoder = new TextDecoder('utf-8');
  9117. let buffer = '';
  9118. while (true) {
  9119. const { done, value } = await reader.read();
  9120. if (done) break;
  9121. buffer += decoder.decode(value, { stream: true });
  9122. const blocks = buffer.split('\n\n');
  9123. buffer = blocks.pop() || '';
  9124. for (const block of blocks) {
  9125. const trimmed = block.trim();
  9126. if (!trimmed) continue;
  9127. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  9128. try {
  9129. const evt = JSON.parse(line);
  9130. handleLivePingEvent(evt);
  9131. } catch (parseErr) {
  9132. console.warn('Ping SSE parse error:', parseErr, line);
  9133. }
  9134. }
  9135. }
  9136. } catch (err) {
  9137. if (err.name === 'AbortError') {
  9138. // User aborted normally
  9139. } else {
  9140. showToast('Ping Error', err.message, 'error');
  9141. }
  9142. } finally {
  9143. pingAbortController = null;
  9144. resetPingButton();
  9145. }
  9146. }
  9147. function handleLivePingEvent(evt) {
  9148. const sentEl = document.getElementById('tools-ping-stat-sent');
  9149. const recvEl = document.getElementById('tools-ping-stat-recv');
  9150. const lossEl = document.getElementById('tools-ping-stat-loss');
  9151. const avgEl = document.getElementById('tools-ping-stat-avg');
  9152. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  9153. const badge = document.getElementById('tools-ping-status-badge');
  9154. const tbody = document.getElementById('tools-ping-tbody');
  9155. const rawEl = document.getElementById('tools-ping-raw');
  9156. if (evt.raw && rawEl) {
  9157. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  9158. rawEl.scrollTop = rawEl.scrollHeight;
  9159. }
  9160. if (evt.type === 'reply') {
  9161. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  9162. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  9163. if (lossEl && evt.packet_loss_pct !== undefined) {
  9164. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  9165. lossEl.className = evt.packet_loss_pct === 0
  9166. ? 'text-base font-bold font-mono text-emerald-400 mt-1'
  9167. : (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');
  9168. }
  9169. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  9170. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  9171. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  9172. }
  9173. if (badge) {
  9174. if (evt.packet_loss_pct === 0) {
  9175. 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';
  9176. badge.innerText = '100% OK';
  9177. } else {
  9178. 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';
  9179. badge.innerText = `${evt.packet_loss_pct.toFixed(0)}% LOSS`;
  9180. }
  9181. }
  9182. if (tbody) {
  9183. const tr = document.createElement('tr');
  9184. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  9185. tr.innerHTML = `
  9186. <td class="py-2 px-3 text-slate-300">#${evt.seq}</td>
  9187. <td class="py-2 px-3 font-semibold text-white">${escapeHtml(evt.from)}</td>
  9188. <td class="py-2 px-3 text-slate-400">${evt.bytes} bytes</td>
  9189. <td class="py-2 px-3 text-slate-300">${evt.ttl}</td>
  9190. <td class="py-2 px-3 font-bold text-amber-300">${evt.time_ms.toFixed(2)} ms</td>
  9191. <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>
  9192. `;
  9193. tbody.appendChild(tr);
  9194. }
  9195. } else if (evt.type === 'timeout') {
  9196. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  9197. if (lossEl && evt.packet_loss_pct !== undefined) {
  9198. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  9199. 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';
  9200. }
  9201. if (badge) {
  9202. 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';
  9203. badge.innerText = `${evt.packet_loss_pct?.toFixed(0) || 100}% LOSS`;
  9204. }
  9205. if (tbody) {
  9206. const tr = document.createElement('tr');
  9207. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs opacity-75';
  9208. tr.innerHTML = `
  9209. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  9210. <td class="py-2 px-3 font-semibold text-slate-500 italic">Request timed out</td>
  9211. <td class="py-2 px-3 text-slate-600">--</td>
  9212. <td class="py-2 px-3 text-slate-600">--</td>
  9213. <td class="py-2 px-3 font-bold text-slate-500">* * *</td>
  9214. <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>
  9215. `;
  9216. tbody.appendChild(tr);
  9217. }
  9218. } else if (evt.type === 'unreach') {
  9219. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  9220. if (lossEl && evt.packet_loss_pct !== undefined) {
  9221. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  9222. lossEl.className = 'text-base font-bold font-mono text-rose-400 mt-1';
  9223. }
  9224. if (badge) {
  9225. 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';
  9226. badge.innerText = 'UNREACHABLE';
  9227. }
  9228. if (tbody) {
  9229. const tr = document.createElement('tr');
  9230. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  9231. tr.innerHTML = `
  9232. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  9233. <td class="py-2 px-3 font-semibold text-rose-400">${escapeHtml(evt.from || 'Gateway')}</td>
  9234. <td class="py-2 px-3 text-slate-600">--</td>
  9235. <td class="py-2 px-3 text-slate-600">--</td>
  9236. <td class="py-2 px-3 font-bold text-rose-400 text-xs">${escapeHtml(evt.message || 'Unreachable')}</td>
  9237. <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>
  9238. `;
  9239. tbody.appendChild(tr);
  9240. }
  9241. } else if (evt.type === 'stats') {
  9242. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  9243. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  9244. if (lossEl && evt.packet_loss_pct !== undefined) lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  9245. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  9246. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  9247. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  9248. }
  9249. } else if (evt.type === 'done') {
  9250. 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');
  9251. }
  9252. }
  9253. async function executeTraceroute(e) {
  9254. if (e) e.preventDefault();
  9255. if (tracerouteAbortController) {
  9256. tracerouteAbortController.abort();
  9257. tracerouteAbortController = null;
  9258. resetTracerouteButton();
  9259. showToast('Traceroute Stopped', 'Traceroute stopped by user', 'info');
  9260. return;
  9261. }
  9262. const target = document.getElementById('tools-tr-target')?.value?.trim();
  9263. const maxHops = parseInt(document.getElementById('tools-tr-maxhops')?.value || '15', 10);
  9264. const protocol = document.getElementById('tools-tr-proto')?.value || 'icmp';
  9265. const iface = document.getElementById('tools-tr-iface')?.value || '';
  9266. const resolve = document.getElementById('tools-tr-resolve')?.checked || false;
  9267. if (!target) {
  9268. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  9269. return;
  9270. }
  9271. clearTracerouteTable();
  9272. const resCard = document.getElementById('tools-tr-results');
  9273. if (resCard) resCard.classList.remove('hidden');
  9274. tracerouteAbortController = new AbortController();
  9275. setTracerouteRunningButton();
  9276. try {
  9277. const res = await fetch(`${API_BASE}/tools/traceroute/stream`, {
  9278. method: 'POST',
  9279. headers: { 'Content-Type': 'application/json' },
  9280. body: JSON.stringify({
  9281. target,
  9282. max_hops: maxHops,
  9283. protocol,
  9284. interface: iface,
  9285. resolve
  9286. }),
  9287. signal: tracerouteAbortController.signal
  9288. });
  9289. if (!res.ok) {
  9290. const errText = await res.text();
  9291. showToast('Traceroute Error', errText || 'Failed to start traceroute', 'error');
  9292. resetTracerouteButton();
  9293. tracerouteAbortController = null;
  9294. return;
  9295. }
  9296. const reader = res.body.getReader();
  9297. const decoder = new TextDecoder('utf-8');
  9298. let buffer = '';
  9299. while (true) {
  9300. const { done, value } = await reader.read();
  9301. if (done) break;
  9302. buffer += decoder.decode(value, { stream: true });
  9303. const blocks = buffer.split('\n\n');
  9304. buffer = blocks.pop() || '';
  9305. for (const block of blocks) {
  9306. const trimmed = block.trim();
  9307. if (!trimmed) continue;
  9308. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  9309. try {
  9310. const evt = JSON.parse(line);
  9311. handleLiveTracerouteEvent(evt);
  9312. } catch (parseErr) {
  9313. console.warn('Traceroute SSE parse error:', parseErr, line);
  9314. }
  9315. }
  9316. }
  9317. } catch (err) {
  9318. if (err.name === 'AbortError') {
  9319. // User aborted normally
  9320. } else {
  9321. showToast('Traceroute Error', err.message, 'error');
  9322. }
  9323. } finally {
  9324. tracerouteAbortController = null;
  9325. resetTracerouteButton();
  9326. }
  9327. }
  9328. function handleLiveTracerouteEvent(evt) {
  9329. const statHops = document.getElementById('tools-tr-hops-count');
  9330. const tbody = document.getElementById('tools-tr-tbody');
  9331. const rawEl = document.getElementById('tools-tr-raw');
  9332. if (evt.raw && rawEl) {
  9333. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  9334. rawEl.scrollTop = rawEl.scrollHeight;
  9335. }
  9336. if (evt.hops_count !== undefined && statHops) {
  9337. statHops.innerText = `${evt.hops_count} Hops`;
  9338. }
  9339. if (evt.type === 'hop' && evt.hop && tbody) {
  9340. const h = evt.hop;
  9341. const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
  9342. const rtt1 = Array.isArray(h.times_ms) && h.times_ms[0] ? `${h.times_ms[0]} ms` : (isTimeout ? '*' : '--');
  9343. const rtt2 = Array.isArray(h.times_ms) && h.times_ms[1] ? `${h.times_ms[1]} ms` : (isTimeout ? '*' : '--');
  9344. const displayHost = h.host && h.host !== h.ip ? `${escapeHtml(h.host)} (${escapeHtml(h.ip || '')})` : escapeHtml(h.ip || (isTimeout ? 'Request timed out' : '--'));
  9345. const tr = document.createElement('tr');
  9346. tr.className = `hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}`;
  9347. tr.innerHTML = `
  9348. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  9349. <td class="py-2.5 px-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${displayHost}</td>
  9350. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt1)}</td>
  9351. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt2)}</td>
  9352. <td class="py-2.5 px-3 text-right">
  9353. ${isTimeout
  9354. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
  9355. : '<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>'}
  9356. </td>
  9357. `;
  9358. tbody.appendChild(tr);
  9359. } else if (evt.type === 'done') {
  9360. showToast('Traceroute Finished', `Traced ${evt.hops_count || 0} hops`, 'info');
  9361. }
  9362. }
  9363. async function executeMTR(e) {
  9364. if (e) e.preventDefault();
  9365. const target = document.getElementById('tools-mtr-target')?.value?.trim();
  9366. const cycles = parseInt(document.getElementById('tools-mtr-count')?.value || '3', 10);
  9367. if (!target) {
  9368. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  9369. return;
  9370. }
  9371. const btn = document.getElementById('tools-mtr-btn');
  9372. const spinner = document.getElementById('tools-mtr-spinner');
  9373. if (btn) btn.disabled = true;
  9374. if (spinner) spinner.classList.remove('hidden');
  9375. try {
  9376. const res = await fetch(`${API_BASE}/tools/mtr`, {
  9377. method: 'POST',
  9378. headers: { 'Content-Type': 'application/json' },
  9379. body: JSON.stringify({ target, count: cycles })
  9380. });
  9381. const data = await res.json();
  9382. if (!res.ok) {
  9383. showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
  9384. return;
  9385. }
  9386. const resCard = document.getElementById('tools-mtr-results');
  9387. if (resCard) resCard.classList.remove('hidden');
  9388. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  9389. const statHops = document.getElementById('tools-mtr-hops-count');
  9390. if (statHops) statHops.innerText = `${hopsCount} Hops`;
  9391. const tbody = document.getElementById('tools-mtr-tbody');
  9392. if (tbody) {
  9393. if (hopsCount > 0) {
  9394. tbody.innerHTML = data.hops.map(h => {
  9395. 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');
  9396. return `
  9397. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  9398. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  9399. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
  9400. <td class="py-2.5 px-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
  9401. <td class="py-2.5 px-3 text-slate-300">${h.sent}</td>
  9402. <td class="py-2.5 px-3 text-slate-300">${h.last_ms.toFixed(1)}</td>
  9403. <td class="py-2.5 px-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)}</td>
  9404. <td class="py-2.5 px-3 text-emerald-400">${h.best_ms.toFixed(1)}</td>
  9405. <td class="py-2.5 px-3 text-rose-400">${h.wrst_ms.toFixed(1)}</td>
  9406. <td class="py-2.5 px-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
  9407. </tr>
  9408. `;
  9409. }).join('');
  9410. } else {
  9411. tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
  9412. }
  9413. }
  9414. const rawEl = document.getElementById('tools-mtr-raw');
  9415. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  9416. showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
  9417. } catch (err) {
  9418. showToast('MTR Error', err.message, 'error');
  9419. } finally {
  9420. if (btn) btn.disabled = false;
  9421. if (spinner) spinner.classList.add('hidden');
  9422. }
  9423. }
  9424. async function executeDNS(e) {
  9425. if (e) e.preventDefault();
  9426. const domain = document.getElementById('tools-dns-domain')?.value?.trim();
  9427. const type = document.getElementById('tools-dns-type')?.value || 'A';
  9428. const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
  9429. if (!domain) {
  9430. showToast('Input Required', 'Please enter a hostname or domain', 'warning');
  9431. return;
  9432. }
  9433. const btn = document.getElementById('tools-dns-btn');
  9434. const spinner = document.getElementById('tools-dns-spinner');
  9435. if (btn) btn.disabled = true;
  9436. if (spinner) spinner.classList.remove('hidden');
  9437. try {
  9438. const res = await fetch(`${API_BASE}/tools/dns`, {
  9439. method: 'POST',
  9440. headers: { 'Content-Type': 'application/json' },
  9441. body: JSON.stringify({ domain, type, server })
  9442. });
  9443. const data = await res.json();
  9444. if (!res.ok) {
  9445. showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
  9446. return;
  9447. }
  9448. const resCard = document.getElementById('tools-dns-results');
  9449. if (resCard) resCard.classList.remove('hidden');
  9450. const metaEl = document.getElementById('tools-dns-meta');
  9451. if (metaEl) metaEl.innerText = `Resolved in ${data.query_time_ms ?? 0} ms via ${escapeHtml(data.server || 'System DNS')}`;
  9452. const tbody = document.getElementById('tools-dns-tbody');
  9453. if (tbody) {
  9454. if (Array.isArray(data.records) && data.records.length > 0) {
  9455. tbody.innerHTML = data.records.map(r => `
  9456. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  9457. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.name)}</td>
  9458. <td class="py-2.5 px-3 text-slate-400">${r.ttl}s</td>
  9459. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.class || 'IN')}</td>
  9460. <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>
  9461. <td class="py-2.5 px-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
  9462. </tr>
  9463. `).join('');
  9464. } else {
  9465. 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>`;
  9466. }
  9467. }
  9468. const rawEl = document.getElementById('tools-dns-raw');
  9469. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  9470. showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
  9471. } catch (err) {
  9472. showToast('DNS Error', err.message, 'error');
  9473. } finally {
  9474. if (btn) btn.disabled = false;
  9475. if (spinner) spinner.classList.add('hidden');
  9476. }
  9477. }
  9478. async function executePortProbe(e) {
  9479. if (e) e.preventDefault();
  9480. const target = document.getElementById('tools-port-target')?.value?.trim();
  9481. const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
  9482. const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
  9483. if (!target || !port) {
  9484. showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
  9485. return;
  9486. }
  9487. const btn = document.getElementById('tools-port-btn');
  9488. const spinner = document.getElementById('tools-port-spinner');
  9489. if (btn) btn.disabled = true;
  9490. if (spinner) spinner.classList.remove('hidden');
  9491. try {
  9492. const res = await fetch(`${API_BASE}/tools/port-probe`, {
  9493. method: 'POST',
  9494. headers: { 'Content-Type': 'application/json' },
  9495. body: JSON.stringify({ target, port, timeout })
  9496. });
  9497. const data = await res.json();
  9498. if (!res.ok) {
  9499. showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
  9500. return;
  9501. }
  9502. const resCard = document.getElementById('tools-port-results');
  9503. if (resCard) resCard.classList.remove('hidden');
  9504. const banner = document.getElementById('tools-port-banner');
  9505. const icon = document.getElementById('tools-port-icon');
  9506. const title = document.getElementById('tools-port-title');
  9507. const sub = document.getElementById('tools-port-sub');
  9508. const latency = document.getElementById('tools-port-latency');
  9509. if (data.open) {
  9510. if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
  9511. if (icon) {
  9512. 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';
  9513. icon.innerText = '✓';
  9514. }
  9515. if (title) {
  9516. title.className = 'text-sm font-bold text-emerald-300';
  9517. title.innerText = `PORT ${port} OPEN / LISTENING`;
  9518. }
  9519. if (sub) {
  9520. sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
  9521. sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
  9522. }
  9523. if (latency) {
  9524. latency.className = 'text-base font-bold font-mono text-emerald-300';
  9525. latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
  9526. }
  9527. } else {
  9528. if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-800/50 flex items-center justify-between';
  9529. if (icon) {
  9530. 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';
  9531. icon.innerText = '✕';
  9532. }
  9533. if (title) {
  9534. title.className = 'text-sm font-bold text-rose-300';
  9535. title.innerText = `PORT ${port} CLOSED / FILTERED`;
  9536. }
  9537. if (sub) {
  9538. sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
  9539. sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
  9540. }
  9541. if (latency) {
  9542. latency.className = 'text-base font-bold font-mono text-slate-500';
  9543. latency.innerText = '--';
  9544. }
  9545. }
  9546. const rawEl = document.getElementById('tools-port-raw');
  9547. 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'}`);
  9548. showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
  9549. } catch (err) {
  9550. showToast('Probe Error', err.message, 'error');
  9551. } finally {
  9552. if (btn) btn.disabled = false;
  9553. if (spinner) spinner.classList.add('hidden');
  9554. }
  9555. }
  9556. // ==========================================
  9557. // DHCP CLIENT (/ip dhcp-client) CONTROLLER
  9558. // ==========================================
  9559. async function loadDHCPClients(showToastMsg = false) {
  9560. try {
  9561. const [clientsRes, sumRes] = await Promise.all([
  9562. fetch(`${API_BASE}/dhcp/clients`),
  9563. fetch(`${API_BASE}/dhcp/clients/summary`)
  9564. ]);
  9565. if (clientsRes.ok) {
  9566. state.dhcpClients = await clientsRes.json();
  9567. }
  9568. if (sumRes.ok) {
  9569. state.dhcpSummary = await sumRes.json();
  9570. }
  9571. renderDHCPClients();
  9572. updateDHCPSummaryCards();
  9573. const bDhcp = document.getElementById('badge-dhcp-client-count');
  9574. if (bDhcp && state.dhcpSummary) {
  9575. bDhcp.innerText = state.dhcpSummary.total_clients || 0;
  9576. }
  9577. if (showToastMsg) {
  9578. showToast('Refreshed', 'DHCP Client telemetry updated', 'info');
  9579. }
  9580. } catch (err) {
  9581. console.error('Failed to load DHCP clients:', err);
  9582. if (showToastMsg) {
  9583. showToast('Notice', 'Unable to fetch DHCP client status', 'warning');
  9584. }
  9585. }
  9586. }
  9587. function updateDHCPSummaryCards() {
  9588. const sum = state.dhcpSummary || {
  9589. total_clients: (state.dhcpClients || []).length,
  9590. bound_clients: (state.dhcpClients || []).filter(c => c.status === 'bound').length,
  9591. searching_clients: (state.dhcpClients || []).filter(c => c.status === 'searching').length,
  9592. disabled_clients: (state.dhcpClients || []).filter(c => !c.enabled).length
  9593. };
  9594. const totalEl = document.getElementById('dhcp-stat-total');
  9595. const boundEl = document.getElementById('dhcp-stat-bound');
  9596. const searchEl = document.getElementById('dhcp-stat-searching');
  9597. const disEl = document.getElementById('dhcp-stat-disabled');
  9598. if (totalEl) totalEl.innerText = sum.total_clients ?? 0;
  9599. if (boundEl) boundEl.innerText = sum.bound_clients ?? 0;
  9600. if (searchEl) searchEl.innerText = sum.searching_clients ?? 0;
  9601. if (disEl) disEl.innerText = sum.disabled_clients ?? 0;
  9602. }
  9603. function renderDHCPClients() {
  9604. const tbody = document.getElementById('dhcp-clients-tbody');
  9605. const emptyState = document.getElementById('dhcp-clients-empty');
  9606. if (!tbody) return;
  9607. const clients = Array.isArray(state.dhcpClients) ? state.dhcpClients : [];
  9608. if (clients.length === 0) {
  9609. tbody.innerHTML = '';
  9610. if (emptyState) emptyState.classList.remove('hidden');
  9611. return;
  9612. }
  9613. if (emptyState) emptyState.classList.add('hidden');
  9614. tbody.innerHTML = clients.map(c => {
  9615. let statusBadge = '';
  9616. if (!c.enabled) {
  9617. 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>';
  9618. } else if (c.status === 'bound') {
  9619. 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>';
  9620. } else if (c.status === 'searching') {
  9621. 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>';
  9622. } else if (c.status === 'stopped') {
  9623. 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>';
  9624. } else {
  9625. 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>`;
  9626. }
  9627. 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>';
  9628. const gwDisplay = c.gateway ? `<span class="text-slate-300">${escapeHtml(c.gateway)}</span>` : '<span class="text-slate-600">--</span>';
  9629. const srvDisplay = c.dhcp_server ? `<span class="text-slate-300">${escapeHtml(c.dhcp_server)}</span>` : '<span class="text-slate-600">--</span>';
  9630. 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>';
  9631. const expDisplay = c.expires_in ? `<span class="text-purple-300">${escapeHtml(c.expires_in)}</span>` : '<span class="text-slate-600">--</span>';
  9632. // Option flags
  9633. const flags = [];
  9634. 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>');
  9635. 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>');
  9636. 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>');
  9637. 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>`);
  9638. return `
  9639. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 text-xs transition">
  9640. <td class="py-3 px-4">
  9641. <div class="flex items-center gap-2">
  9642. <span class="font-bold text-white text-sm">${escapeHtml(c.interface)}</span>
  9643. ${c.comment ? `<span class="text-[11px] text-slate-400 font-sans italic">(${escapeHtml(c.comment)})</span>` : ''}
  9644. </div>
  9645. </td>
  9646. <td class="py-3 px-4">${statusBadge}</td>
  9647. <td class="py-3 px-4 font-mono">${ipDisplay}</td>
  9648. <td class="py-3 px-4 font-mono">${gwDisplay}</td>
  9649. <td class="py-3 px-4 font-mono">${srvDisplay}</td>
  9650. <td class="py-3 px-4 font-mono text-[11px]">${dnsDisplay}</td>
  9651. <td class="py-3 px-4 font-mono text-[11px]">${expDisplay}</td>
  9652. <td class="py-3 px-4">
  9653. <div class="flex flex-wrap gap-1 font-mono">${flags.join('')}</div>
  9654. </td>
  9655. <td class="py-3 px-4 text-right space-x-1.5 font-sans whitespace-nowrap">
  9656. ${c.enabled ? `
  9657. <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>
  9658. <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>
  9659. <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>
  9660. ` : `
  9661. <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>
  9662. `}
  9663. <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>
  9664. <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>
  9665. </td>
  9666. </tr>
  9667. `;
  9668. }).join('');
  9669. }
  9670. function openDHCPClientModal(clientId = null) {
  9671. const modal = document.getElementById('modal-dhcp-client');
  9672. if (!modal) return;
  9673. const title = document.getElementById('modal-dhcp-title');
  9674. const idInput = document.getElementById('modal-dhcp-id');
  9675. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  9676. const distInput = document.getElementById('modal-dhcp-distance');
  9677. const commentInput = document.getElementById('modal-dhcp-comment');
  9678. const defRouteCheck = document.getElementById('modal-dhcp-def-route');
  9679. const peerDnsCheck = document.getElementById('modal-dhcp-peer-dns');
  9680. const peerNtpCheck = document.getElementById('modal-dhcp-peer-ntp');
  9681. const enabledCheck = document.getElementById('modal-dhcp-enabled');
  9682. // Populate interfaces
  9683. if (ifaceSelect) {
  9684. let opts = '<option value="">Select interface...</option>';
  9685. const allIfaces = state.interfaces || [];
  9686. const allVlans = state.vlans || [];
  9687. const usedIfaces = new Set((state.dhcpClients || []).map(c => c.interface));
  9688. // Group 1: Physical & Bridge Interfaces
  9689. opts += '<optgroup label="Physical & Bridge Interfaces">';
  9690. allIfaces.forEach(i => {
  9691. const isConfigured = usedIfaces.has(i.name) ? ' (Configured)' : '';
  9692. opts += `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} [${escapeHtml(i.role || i.type)}]${isConfigured}</option>`;
  9693. });
  9694. opts += '</optgroup>';
  9695. // Group 2: VLAN Interfaces
  9696. if (allVlans.length > 0) {
  9697. opts += '<optgroup label="802.1Q VLAN Sub-interfaces">';
  9698. allVlans.forEach(v => {
  9699. const isConfigured = usedIfaces.has(v.name) ? ' (Configured)' : '';
  9700. opts += `<option value="${escapeHtml(v.name)}">${escapeHtml(v.name)} (VLAN ${v.vlan_id})${isConfigured}</option>`;
  9701. });
  9702. opts += '</optgroup>';
  9703. }
  9704. ifaceSelect.innerHTML = opts;
  9705. }
  9706. if (clientId) {
  9707. const client = (state.dhcpClients || []).find(c => c.id === clientId);
  9708. if (client) {
  9709. if (title) title.innerText = `Edit DHCP Client: ${client.interface}`;
  9710. if (idInput) idInput.value = client.id;
  9711. if (ifaceSelect) {
  9712. ifaceSelect.value = client.interface;
  9713. ifaceSelect.disabled = true; // interface cannot be changed on edit
  9714. }
  9715. if (distInput) distInput.value = client.default_route_distance || 1;
  9716. if (commentInput) commentInput.value = client.comment || '';
  9717. if (defRouteCheck) defRouteCheck.checked = client.add_default_route !== false;
  9718. if (peerDnsCheck) peerDnsCheck.checked = client.use_peer_dns !== false;
  9719. if (peerNtpCheck) peerNtpCheck.checked = client.use_peer_ntp !== false;
  9720. if (enabledCheck) enabledCheck.checked = client.enabled !== false;
  9721. }
  9722. } else {
  9723. if (title) title.innerText = 'Add DHCP Client';
  9724. if (idInput) idInput.value = '';
  9725. if (ifaceSelect) {
  9726. ifaceSelect.value = '';
  9727. ifaceSelect.disabled = false;
  9728. }
  9729. if (distInput) distInput.value = 1;
  9730. if (commentInput) commentInput.value = '';
  9731. if (defRouteCheck) defRouteCheck.checked = true;
  9732. if (peerDnsCheck) peerDnsCheck.checked = true;
  9733. if (peerNtpCheck) peerNtpCheck.checked = true;
  9734. if (enabledCheck) enabledCheck.checked = true;
  9735. }
  9736. modal.classList.remove('hidden');
  9737. }
  9738. function openDHCPClientModalForIface(ifaceName) {
  9739. openDHCPClientModal();
  9740. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  9741. if (ifaceSelect && ifaceName) {
  9742. ifaceSelect.value = ifaceName;
  9743. }
  9744. }
  9745. function closeDHCPClientModal() {
  9746. const modal = document.getElementById('modal-dhcp-client');
  9747. if (modal) modal.classList.add('hidden');
  9748. }
  9749. async function submitSaveDHCPClient(e) {
  9750. if (e) e.preventDefault();
  9751. const id = document.getElementById('modal-dhcp-id')?.value;
  9752. const iface = document.getElementById('modal-dhcp-iface')?.value?.trim();
  9753. const distance = parseInt(document.getElementById('modal-dhcp-distance')?.value || '1', 10);
  9754. const comment = document.getElementById('modal-dhcp-comment')?.value?.trim() || '';
  9755. const defRoute = document.getElementById('modal-dhcp-def-route')?.checked ?? true;
  9756. const peerDns = document.getElementById('modal-dhcp-peer-dns')?.checked ?? true;
  9757. const peerNtp = document.getElementById('modal-dhcp-peer-ntp')?.checked ?? true;
  9758. const enabled = document.getElementById('modal-dhcp-enabled')?.checked ?? true;
  9759. if (!id && !iface) {
  9760. showToast('Input Required', 'Please select an interface for the DHCP client', 'warning');
  9761. return;
  9762. }
  9763. try {
  9764. let res;
  9765. if (id) {
  9766. // PUT update
  9767. res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  9768. method: 'PUT',
  9769. headers: { 'Content-Type': 'application/json' },
  9770. body: JSON.stringify({
  9771. enabled,
  9772. add_default_route: defRoute,
  9773. default_route_distance: distance,
  9774. use_peer_dns: peerDns,
  9775. use_peer_ntp: peerNtp,
  9776. comment
  9777. })
  9778. });
  9779. } else {
  9780. // POST create
  9781. res = await fetch(`${API_BASE}/dhcp/clients`, {
  9782. method: 'POST',
  9783. headers: { 'Content-Type': 'application/json' },
  9784. body: JSON.stringify({
  9785. interface: iface,
  9786. enabled,
  9787. add_default_route: defRoute,
  9788. default_route_distance: distance,
  9789. use_peer_dns: peerDns,
  9790. use_peer_ntp: peerNtp,
  9791. comment
  9792. })
  9793. });
  9794. }
  9795. const data = await res.json();
  9796. if (!res.ok) {
  9797. showToast('Error', data.error || 'Failed to save DHCP client', 'error');
  9798. return;
  9799. }
  9800. closeDHCPClientModal();
  9801. showToast('Success', id ? 'DHCP Client updated successfully' : `DHCP Client activated on ${iface}`, 'success');
  9802. await loadDHCPClients();
  9803. fetchData(); // refresh interfaces list with new lease/status
  9804. } catch (err) {
  9805. showToast('Error', err.message, 'error');
  9806. }
  9807. }
  9808. async function toggleDHCPClientState(id, enabled) {
  9809. try {
  9810. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/state`, {
  9811. method: 'POST',
  9812. headers: { 'Content-Type': 'application/json' },
  9813. body: JSON.stringify({ enabled })
  9814. });
  9815. const data = await res.json();
  9816. if (!res.ok) {
  9817. showToast('Error', data.error || 'Failed to toggle client state', 'error');
  9818. return;
  9819. }
  9820. showToast('Updated', `DHCP client ${enabled ? 'enabled' : 'disabled'}`, 'info');
  9821. await loadDHCPClients();
  9822. fetchData();
  9823. } catch (err) {
  9824. showToast('Error', err.message, 'error');
  9825. }
  9826. }
  9827. async function renewDHCPClient(id) {
  9828. try {
  9829. showToast('Renewing...', 'Requesting DHCP lease renewal from upstream server', 'info');
  9830. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/renew`, {
  9831. method: 'POST'
  9832. });
  9833. const data = await res.json();
  9834. if (!res.ok) {
  9835. showToast('Error', data.error || 'Failed to renew lease', 'error');
  9836. return;
  9837. }
  9838. showToast('Lease Renewed', 'DHCP renewal signal sent successfully', 'success');
  9839. setTimeout(() => {
  9840. loadDHCPClients();
  9841. fetchData();
  9842. }, 1500);
  9843. } catch (err) {
  9844. showToast('Error', err.message, 'error');
  9845. }
  9846. }
  9847. async function releaseDHCPClient(id) {
  9848. try {
  9849. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/release`, {
  9850. method: 'POST'
  9851. });
  9852. const data = await res.json();
  9853. if (!res.ok) {
  9854. showToast('Error', data.error || 'Failed to release lease', 'error');
  9855. return;
  9856. }
  9857. showToast('Lease Released', 'DHCP lease released from upstream server', 'info');
  9858. await loadDHCPClients();
  9859. fetchData();
  9860. } catch (err) {
  9861. showToast('Error', err.message, 'error');
  9862. }
  9863. }
  9864. async function deleteDHCPClient(id, ifaceName) {
  9865. if (!confirm(`Are you sure you want to remove the DHCP Client on ${ifaceName}? The interface will release its dynamic IP.`)) {
  9866. return;
  9867. }
  9868. try {
  9869. const res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  9870. method: 'DELETE'
  9871. });
  9872. const data = await res.json();
  9873. if (!res.ok) {
  9874. showToast('Error', data.error || 'Failed to delete DHCP client', 'error');
  9875. return;
  9876. }
  9877. showToast('Deleted', `DHCP client removed from ${ifaceName}`, 'info');
  9878. await loadDHCPClients();
  9879. fetchData();
  9880. } catch (err) {
  9881. showToast('Error', err.message, 'error');
  9882. }
  9883. }
  9884. // ==================== UNIVERSAL TABLE ORDERING / SORTING (WINBOX / WEBFIG STYLE) ====================
  9885. function initTableSorting() {
  9886. document.querySelectorAll('table').forEach(setupSortableTable);
  9887. }
  9888. function setupSortableTable(table) {
  9889. const thead = table.querySelector('thead');
  9890. const tbody = table.querySelector('tbody');
  9891. if (!thead || !tbody) return;
  9892. const headerRows = thead.querySelectorAll('tr');
  9893. if (headerRows.length === 0) return;
  9894. const ths = headerRows[headerRows.length - 1].querySelectorAll('th');
  9895. ths.forEach((th, colIdx) => {
  9896. if (th._sortBound) return;
  9897. th._sortBound = true;
  9898. const rawText = th.innerText.trim().toLowerCase();
  9899. const isActionsCol = rawText === 'actions' || (rawText === 'action' && th.classList.contains('text-right'));
  9900. const isCheckboxCol = !!th.querySelector('input[type="checkbox"]');
  9901. const isExpandCol = (th.classList.contains('w-8') || th.classList.contains('w-6')) && !rawText;
  9902. const isExplicitNoSort = th.classList.contains('no-sort') || th.getAttribute('data-sortable') === 'false';
  9903. if (isActionsCol || isCheckboxCol || isExpandCol || isExplicitNoSort) {
  9904. return;
  9905. }
  9906. th.classList.add('table-sortable', 'group');
  9907. if (!th.title) th.title = 'Click to sort (Ascending / Descending / Default)';
  9908. let icon = th.querySelector('.table-sort-icon');
  9909. if (!icon) {
  9910. icon = document.createElement('span');
  9911. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  9912. icon.innerHTML = '⇅';
  9913. th.appendChild(icon);
  9914. }
  9915. th.addEventListener('click', (e) => {
  9916. if (e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON' || e.target.closest('button, input')) return;
  9917. handleHeaderClick(table, th, colIdx);
  9918. });
  9919. });
  9920. if (!tbody._sortObserved) {
  9921. tbody._sortObserved = true;
  9922. let sortDebounceTimer = null;
  9923. const observer = new MutationObserver((mutations) => {
  9924. if (tbody._isSorting) return;
  9925. const hasChildChanges = mutations.some(m => m.type === 'childList' && m.addedNodes.length > 0);
  9926. if (!hasChildChanges) return;
  9927. clearTimeout(sortDebounceTimer);
  9928. sortDebounceTimer = setTimeout(() => {
  9929. if (tbody._isSorting) return;
  9930. if (table._activeSort && table._activeSort.dir !== 'none') {
  9931. applyTableSort(table, table._activeSort.colIdx, table._activeSort.dir, false);
  9932. } else {
  9933. tagOriginalRowOrder(tbody);
  9934. }
  9935. }, 10);
  9936. });
  9937. observer.observe(tbody, { childList: true });
  9938. }
  9939. tagOriginalRowOrder(tbody);
  9940. }
  9941. function tagOriginalRowOrder(tbody) {
  9942. let idx = 0;
  9943. Array.from(tbody.children).forEach(tr => {
  9944. if (!tr.querySelector('td[colspan]')) {
  9945. if (!tr.hasAttribute('data-orig-idx')) {
  9946. tr.setAttribute('data-orig-idx', idx++);
  9947. }
  9948. }
  9949. });
  9950. }
  9951. function handleHeaderClick(table, th, colIdx) {
  9952. const currentSort = table._activeSort || { colIdx: -1, dir: 'none' };
  9953. let newDir = 'asc';
  9954. if (currentSort.colIdx === colIdx) {
  9955. if (currentSort.dir === 'asc') newDir = 'desc';
  9956. else if (currentSort.dir === 'desc') newDir = 'none';
  9957. else newDir = 'asc';
  9958. } else {
  9959. newDir = 'asc';
  9960. }
  9961. table._activeSort = { colIdx, dir: newDir };
  9962. updateHeaderIcons(table, colIdx, newDir);
  9963. applyTableSort(table, colIdx, newDir, true);
  9964. }
  9965. function updateHeaderIcons(table, activeColIdx, dir) {
  9966. const thead = table.querySelector('thead');
  9967. if (!thead) return;
  9968. const ths = thead.querySelectorAll('th');
  9969. ths.forEach((th, idx) => {
  9970. const icon = th.querySelector('.table-sort-icon');
  9971. if (!icon) return;
  9972. if (idx === activeColIdx && dir !== 'none') {
  9973. icon.innerHTML = dir === 'asc' ? '▲' : '▼';
  9974. icon.className = 'table-sort-icon text-cyan-400 font-bold opacity-100';
  9975. th.classList.add('table-sorted-active');
  9976. } else {
  9977. icon.innerHTML = '⇅';
  9978. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  9979. th.classList.remove('table-sorted-active');
  9980. }
  9981. });
  9982. }
  9983. function applyTableSort(table, colIdx, dir, userInitiated) {
  9984. const tbody = table.querySelector('tbody');
  9985. if (!tbody || tbody.children.length <= 1) return;
  9986. tbody._isSorting = true;
  9987. tagOriginalRowOrder(tbody);
  9988. // Group parent rows and any attached drawer/sub-rows
  9989. const groups = [];
  9990. let currentGroup = null;
  9991. Array.from(tbody.children).forEach(tr => {
  9992. if (tr.querySelector('td[colspan]')) {
  9993. if (currentGroup) {
  9994. currentGroup.subRows.push(tr);
  9995. } else {
  9996. groups.push({ mainRow: tr, subRows: [] });
  9997. }
  9998. } else {
  9999. currentGroup = { mainRow: tr, subRows: [] };
  10000. groups.push(currentGroup);
  10001. }
  10002. });
  10003. if (dir === 'none') {
  10004. groups.sort((a, b) => {
  10005. const idxA = parseInt(a.mainRow.getAttribute('data-orig-idx') || '0', 10);
  10006. const idxB = parseInt(b.mainRow.getAttribute('data-orig-idx') || '0', 10);
  10007. return idxA - idxB;
  10008. });
  10009. } else {
  10010. groups.sort((a, b) => {
  10011. const cellA = a.mainRow.children[colIdx];
  10012. const cellB = b.mainRow.children[colIdx];
  10013. const res = compareTableCells(cellA, cellB);
  10014. return dir === 'asc' ? res : -res;
  10015. });
  10016. }
  10017. // Re-append rows in sorted order
  10018. groups.forEach(g => {
  10019. tbody.appendChild(g.mainRow);
  10020. g.subRows.forEach(sub => tbody.appendChild(sub));
  10021. });
  10022. tbody._isSorting = false;
  10023. }
  10024. function getCellRawText(cell) {
  10025. if (!cell) return '';
  10026. if (cell.hasAttribute('data-sort-value')) return cell.getAttribute('data-sort-value');
  10027. const input = cell.querySelector('input, select');
  10028. if (input) {
  10029. if (input.type === 'checkbox') return input.checked ? '1' : '0';
  10030. return input.value;
  10031. }
  10032. return cell.innerText.trim();
  10033. }
  10034. function parseTrafficToNumber(str) {
  10035. const m = str.match(/^([\d.,]+)\s*([KMGTkmgt]?[iI]?[Bb](?:ps|\/s)?)/);
  10036. if (!m) return null;
  10037. const num = parseFloat(m[1].replace(/,/g, ''));
  10038. if (isNaN(num)) return null;
  10039. const unit = m[2].toUpperCase();
  10040. let mult = 1;
  10041. if (unit.startsWith('K')) mult = 1024;
  10042. else if (unit.startsWith('M')) mult = 1024 * 1024;
  10043. else if (unit.startsWith('G')) mult = 1024 * 1024 * 1024;
  10044. else if (unit.startsWith('T')) mult = 1024 * 1024 * 1024 * 1024;
  10045. return num * mult;
  10046. }
  10047. function parseIpToNumber(str) {
  10048. const clean = str.replace(/^[!~]/, '').trim();
  10049. const m = clean.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,2}))?/);
  10050. if (!m) return null;
  10051. const o1 = parseInt(m[1], 10);
  10052. const o2 = parseInt(m[2], 10);
  10053. const o3 = parseInt(m[3], 10);
  10054. const o4 = parseInt(m[4], 10);
  10055. if (o1 > 255 || o2 > 255 || o3 > 255 || o4 > 255) return null;
  10056. return ((o1 * 256 + o2) * 256 + o3) * 256 + o4;
  10057. }
  10058. function parseCompoundPackets(str) {
  10059. const m = str.match(/^([\d,]+)p/);
  10060. if (!m) return null;
  10061. return parseInt(m[1].replace(/,/g, ''), 10);
  10062. }
  10063. function compareTableCells(cellA, cellB) {
  10064. const a = getCellRawText(cellA);
  10065. const b = getCellRawText(cellB);
  10066. if (a === '' && b !== '') return 1;
  10067. if (b === '' && a !== '') return -1;
  10068. if (a === b) return 0;
  10069. // 1. IP Addresses / CIDR
  10070. const ipA = parseIpToNumber(a);
  10071. const ipB = parseIpToNumber(b);
  10072. if (ipA !== null && ipB !== null) return ipA - ipB;
  10073. // 2. Packet counts (e.g. "1,250p / 45 KB")
  10074. const pktA = parseCompoundPackets(a);
  10075. const pktB = parseCompoundPackets(b);
  10076. if (pktA !== null && pktB !== null) return pktA - pktB;
  10077. // 3. Traffic / Throughput / Bytes (e.g. "1.2 MB", "500 KiB", "10 Gbps")
  10078. const trafA = parseTrafficToNumber(a);
  10079. const trafB = parseTrafficToNumber(b);
  10080. if (trafA !== null && trafB !== null) return trafA - trafB;
  10081. // 4. Numbers with '#' or formatted with commas (e.g. "#1", "24", "1,200")
  10082. const cleanNumA = a.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  10083. const cleanNumB = b.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  10084. const numA = Number(cleanNumA);
  10085. const numB = Number(cleanNumB);
  10086. if (!isNaN(numA) && !isNaN(numB) && cleanNumA !== '' && cleanNumB !== '') {
  10087. return numA - numB;
  10088. }
  10089. // 5. Natural case-insensitive string compare
  10090. return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
  10091. }
  10092. // Global observer for dynamically injected tables (e.g. inside modals or drawers)
  10093. if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {
  10094. const docTableObserver = new MutationObserver((mutations) => {
  10095. let needsInit = false;
  10096. for (const m of mutations) {
  10097. for (const node of m.addedNodes) {
  10098. if (node.nodeType === 1) {
  10099. if (node.tagName === 'TABLE' || (node.querySelector && node.querySelector('table'))) {
  10100. needsInit = true;
  10101. break;
  10102. }
  10103. }
  10104. }
  10105. if (needsInit) break;
  10106. }
  10107. if (needsInit) {
  10108. initTableSorting();
  10109. }
  10110. });
  10111. docTableObserver.observe(document.body || document.documentElement, { childList: true, subtree: true });
  10112. }