app.js 415 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872
  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. fetchData();
  64. // Live polling every 2.5 seconds
  65. setInterval(() => {
  66. if (state.isPolling) {
  67. fetchData(false);
  68. }
  69. }, 2500);
  70. });
  71. // Navigation Handler
  72. function navigate(tabName) {
  73. if (tabName === 'dynamic-routing' || tabName === 'routing') {
  74. navigate('bgp');
  75. return;
  76. }
  77. if (tabName === 'vlans') {
  78. navigate('interfaces');
  79. return;
  80. }
  81. state.activeTab = tabName;
  82. window.location.hash = tabName;
  83. // Update nav links styling
  84. document.querySelectorAll('.nav-link').forEach(link => {
  85. 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';
  86. });
  87. const activeNav = document.getElementById(`nav-${tabName}`);
  88. if (activeNav) {
  89. 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';
  90. }
  91. // Update page headers
  92. const titles = {
  93. dashboard: { title: 'Dashboard Overview', sub: 'Live router performance and network telemetry' },
  94. interfaces: { title: 'Network Interfaces', sub: 'Interface Table View' },
  95. 'dhcp-client': { title: 'DHCP Client', sub: 'DHCP Client List' },
  96. bridge: { title: 'Bridge Interfaces', sub: 'IEEE 802.1D / 802.1Q VLAN-aware Layer 2 switching, RSTP & hardware forwarding (FDB)' },
  97. vlans: { title: 'VLAN Virtual Networks', sub: 'IEEE 802.1Q sub-interface segmentation and routing' },
  98. firewall: { title: 'Network Firewall', sub: 'Stateful packet inspection, NAT, traffic mangle, address lists & connection tracking' },
  99. routes: { title: 'Routing & Policy', sub: 'Routing tables, static routes (DAS/DAC), and policy routing rules' },
  100. bgp: { title: 'BGP Routing (/routing bgp)', sub: 'FRRouting BGP peering sessions, advertised networks, and BGP routing table (RIB)' },
  101. ospf: { title: 'OSPF Routing (/routing ospf)', sub: 'FRRouting OSPFv2 link-state routing, dynamic neighbor adjacencies, and multi-area topology' },
  102. 'routing-filters': { title: 'Routing Filters (/routing filter)', sub: 'Route filter chains, prefix matching, BGP community maps & policy-based path control' },
  103. 'dynamic-routing': { title: 'BGP Routing (/routing bgp)', sub: 'FRRouting dynamic routing' },
  104. ppp: { title: 'PPP Servers & Secrets', sub: 'Subscriber authentication, dynamic IP pools and VPN access concentrators' },
  105. eoip: { title: 'EoIP Tunnels', sub: 'Ethernet over IP (EoIP / GRETAP) Layer 2 encapsulation & transparent network bridging' },
  106. pppoe: { title: 'PPPoE Client WAN', sub: 'Point-to-Point Protocol over Ethernet WAN access' },
  107. wireguard: { title: 'WireGuard VPN', sub: 'High-performance cryptographic Layer 3 tunnels with ChaCha20-Poly1305 key exchange' },
  108. ipsec: { title: 'IPSec (IKEv2) strongSwan', sub: 'Enterprise Site-to-Site & Roadwarrior IPSec controller' },
  109. l2tp: { title: 'L2TP VPN Client', sub: 'Layer 2 Tunneling Protocol via xl2tpd' },
  110. pptp: { title: 'PPTP VPN Client', sub: 'Point-to-Point Tunneling Protocol with MPPE-128 encryption' },
  111. tools: { title: 'Diagnostic & Troubleshooting Tools', sub: 'Network latency analysis, ICMP/MTR telemetry, path tracing, DNS resolution and TCP probing' },
  112. persistence: { title: 'Debian Configuration', sub: 'Native /etc/network/interfaces.d/ persistence manager' }
  113. };
  114. const header = titles[tabName] || titles.dashboard;
  115. const pTitle = document.getElementById('page-title');
  116. if (pTitle) pTitle.innerText = header.title;
  117. const pSub = document.getElementById('page-subtitle');
  118. if (pSub) pSub.innerText = header.sub;
  119. // Toggle sections dynamically for all section elements
  120. document.querySelectorAll('main section[id^="section-"]').forEach(el => {
  121. if (el.id === `section-${tabName}`) {
  122. el.classList.remove('hidden');
  123. } else {
  124. el.classList.add('hidden');
  125. }
  126. });
  127. if (tabName === 'bridge') loadBridge();
  128. if (tabName === 'firewall') loadFirewall();
  129. if (tabName === 'routes') loadRoutes();
  130. if (tabName === 'bgp') {
  131. loadDynamicRouting();
  132. switchBgpSubTab(state.activeBgpSubTab || 'bgp-peers');
  133. }
  134. if (tabName === 'ospf') {
  135. loadDynamicRouting();
  136. switchOspfSubTab(state.activeOspfSubTab || 'ospf-ifaces');
  137. }
  138. if (tabName === 'routing-filters') loadDynamicRouting();
  139. if (tabName === 'dynamic-routing') loadDynamicRouting();
  140. if (tabName === 'ppp') loadPPP();
  141. if (tabName === 'eoip') loadEoIP();
  142. if (tabName === 'persistence') loadDebianConfig();
  143. if (tabName === 'pppoe') loadPPPoE();
  144. if (tabName === 'wireguard') loadWireGuard();
  145. if (tabName === 'ipsec') loadIPSec();
  146. if (tabName === 'l2tp') loadL2TP();
  147. if (tabName === 'pptp') loadPPTP();
  148. if (tabName === 'tools') loadToolsView();
  149. if (tabName === 'dhcp-client') loadDHCPClients();
  150. }
  151. // Fetch all core system, network and VPN telemetry
  152. async function fetchData(isManual = false) {
  153. const spinner = document.getElementById('refresh-spinner');
  154. if (isManual && spinner) spinner.classList.add('animate-spin');
  155. try {
  156. const [statusRes, ifacesRes, vlansRes, vpnRes, fwRes, dynRes, brSummaryRes, dhcpSumRes, dhcpClientsRes] = await Promise.all([
  157. fetch(`${API_BASE}/system/status`),
  158. fetch(`${API_BASE}/interfaces`),
  159. fetch(`${API_BASE}/vlans`),
  160. fetch(`${API_BASE}/vpn/status`),
  161. fetch(`${API_BASE}/firewall/summary`),
  162. fetch(`${API_BASE}/routing/dynamic/summary`),
  163. fetch(`${API_BASE}/bridge/summary`),
  164. fetch(`${API_BASE}/dhcp/clients/summary`),
  165. fetch(`${API_BASE}/dhcp/clients`)
  166. ]);
  167. if (dhcpSumRes && dhcpSumRes.ok) {
  168. state.dhcpSummary = await dhcpSumRes.json();
  169. const bDhcp = document.getElementById('badge-dhcp-client-count');
  170. if (bDhcp) bDhcp.innerText = state.dhcpSummary?.total_clients || 0;
  171. }
  172. if (dhcpClientsRes && dhcpClientsRes.ok) {
  173. state.dhcpClients = await dhcpClientsRes.json();
  174. }
  175. if (brSummaryRes.ok) {
  176. state.bridgeSummary = await brSummaryRes.json();
  177. const bBridge = document.getElementById('badge-bridge-count');
  178. if (bBridge) bBridge.innerText = state.bridgeSummary?.bridges_count || 0;
  179. const sBr = document.getElementById('bridge-stat-bridges');
  180. if (sBr) sBr.innerText = state.bridgeSummary?.bridges_count || 0;
  181. const sPorts = document.getElementById('bridge-stat-ports');
  182. if (sPorts) sPorts.innerText = state.bridgeSummary?.ports_count || 0;
  183. const sHosts = document.getElementById('bridge-stat-hosts');
  184. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  185. }
  186. if (statusRes.ok) state.systemStatus = await statusRes.json();
  187. if (ifacesRes.ok) {
  188. const ifacesData = await ifacesRes.json();
  189. const rawIfaces = Array.isArray(ifacesData) ? ifacesData : [];
  190. state.interfaces = rawIfaces.filter(i => {
  191. if (!i.name) return false;
  192. if (i.name.startsWith('ep_')) return false;
  193. return !['gre0', 'gretap0', 'erspan0', 'sit0', 'tunl0', 'ip6tnl0', 'ip6gre0', 'ip6erspan0'].includes(i.name);
  194. });
  195. try { populateToolsInterfaces(); } catch (e) {}
  196. }
  197. if (vlansRes.ok) {
  198. const vlansData = await vlansRes.json();
  199. state.vlans = Array.isArray(vlansData) ? vlansData : [];
  200. }
  201. if (vpnRes.ok) state.vpnStatus = await vpnRes.json();
  202. if (fwRes && fwRes.ok) state.fwSummary = await fwRes.json();
  203. if (dynRes && dynRes.ok) state.dynSummary = await dynRes.json();
  204. updateSystemMetrics();
  205. updateBadges();
  206. if (state.activeTab === 'dashboard') renderDashboard();
  207. if (state.activeTab === 'interfaces') renderInterfacesList();
  208. if (state.activeTab === 'vlans') renderVlansList();
  209. if (state.activeTab === 'firewall') loadFirewall(false);
  210. if (state.activeTab === 'routes') loadRoutes(false);
  211. if (state.activeTab === 'dynamic-routing' || state.activeTab === 'bgp' || state.activeTab === 'ospf') loadDynamicRouting(false);
  212. if (state.activeTab === 'ppp') loadPPP(false);
  213. if (state.activeTab === 'eoip') loadEoIP(false);
  214. if (state.activeTab === 'pppoe') loadPPPoE(false);
  215. if (state.activeTab === 'wireguard') loadWireGuard(false);
  216. if (state.activeTab === 'ipsec') loadIPSec(false);
  217. if (state.activeTab === 'l2tp') loadL2TP(false);
  218. if (state.activeTab === 'pptp') loadPPTP(false);
  219. if (state.activeTab === 'dhcp-client') loadDHCPClients(false);
  220. } catch (err) {
  221. console.error('Failed to fetch router state:', err);
  222. } finally {
  223. if (isManual && spinner) {
  224. setTimeout(() => spinner.classList.remove('animate-spin'), 300);
  225. }
  226. }
  227. }
  228. // Update Top KPI and Sidebar Telemetry
  229. function updateSystemMetrics() {
  230. const s = state.systemStatus;
  231. const v = state.vpnStatus;
  232. if (!s) return;
  233. // Sidebar Host & Uptime
  234. const sideHost = document.getElementById('side-hostname');
  235. if (sideHost) sideHost.innerText = s.hostname || 'debian-lxc';
  236. const sideUp = document.getElementById('side-uptime');
  237. if (sideUp) sideUp.innerText = s.uptime_human || '0m';
  238. const sideGw = document.getElementById('side-gateway-ip');
  239. if (sideGw) sideGw.innerText = s.default_gateway ? `GW: ${s.default_gateway}` : 'GW: Isolated';
  240. // Compute CPU Metrics
  241. let cpuPct = 0;
  242. if (s.cpu_pct !== undefined) {
  243. cpuPct = s.cpu_pct;
  244. } else if (s.cpu_load && s.cpu_load.length > 0) {
  245. const cores = s.cpu_cores || 1;
  246. cpuPct = Math.min(100, Math.round((parseFloat(s.cpu_load[0]) / cores) * 100));
  247. }
  248. const cpuPctStr = `${cpuPct.toFixed(1)}%`;
  249. const cpuWidth = `${Math.max(3, Math.min(100, cpuPct))}%`;
  250. const loadStr = s.cpu_load ? s.cpu_load.join(', ') : '-';
  251. // Sidebar CPU
  252. const sideCpuVal = document.getElementById('side-cpu-val');
  253. if (sideCpuVal) sideCpuVal.innerText = cpuPctStr;
  254. const sideCpuBar = document.getElementById('side-cpu-bar');
  255. if (sideCpuBar) {
  256. sideCpuBar.style.width = cpuWidth;
  257. sideCpuBar.title = `Container: ${cpuPctStr} | Host Loadavg: ${loadStr} (${s.cpu_cores || 1} cores)`;
  258. }
  259. // Dashboard CPU Card
  260. const dashCpuVal = document.getElementById('dash-cpu-val');
  261. if (dashCpuVal) dashCpuVal.innerText = cpuPctStr;
  262. const dashCpuBar = document.getElementById('dash-cpu-bar');
  263. if (dashCpuBar) {
  264. dashCpuBar.style.width = cpuWidth;
  265. if (cpuPct > 85) {
  266. dashCpuBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  267. } else if (cpuPct > 65) {
  268. dashCpuBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  269. } else {
  270. dashCpuBar.className = 'h-full rounded-full bg-emerald-500 transition-all duration-500';
  271. }
  272. }
  273. const dashCpuCores = document.getElementById('dash-cpu-cores');
  274. if (dashCpuCores) dashCpuCores.innerText = `${s.cpu_cores || 1} Cores`;
  275. const dashCpuLoad = document.getElementById('dash-cpu-load');
  276. if (dashCpuLoad) dashCpuLoad.innerText = loadStr;
  277. const dashCpuStatus = document.getElementById('dash-cpu-status');
  278. if (dashCpuStatus) {
  279. if (cpuPct > 85) {
  280. dashCpuStatus.innerText = 'High';
  281. dashCpuStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  282. } else if (cpuPct > 65) {
  283. dashCpuStatus.innerText = 'Heavy';
  284. dashCpuStatus.className = 'text-[11px] font-semibold text-amber-400 uppercase px-2 py-0.5 rounded bg-amber-500/10';
  285. } else {
  286. dashCpuStatus.innerText = 'Normal';
  287. dashCpuStatus.className = 'text-[11px] font-semibold text-emerald-400 uppercase px-2 py-0.5 rounded bg-emerald-500/10';
  288. }
  289. }
  290. // Compute RAM Metrics
  291. const memPct = Math.round(s.mem_usage_pct || 0);
  292. const memPctStr = `${memPct}%`;
  293. const memWidth = `${Math.max(3, Math.min(100, memPct))}%`;
  294. const usedMB = s.mem_used_mb || 0;
  295. const totalMB = s.mem_total_mb || 0;
  296. const freeMB = totalMB > usedMB ? totalMB - usedMB : 0;
  297. function fmtMemMB(mb) {
  298. if (mb >= 1024) {
  299. return `${(mb / 1024).toFixed(1)} GB`;
  300. }
  301. return `${mb} MB`;
  302. }
  303. // Sidebar RAM
  304. const sideRamVal = document.getElementById('side-ram-val');
  305. if (sideRamVal) sideRamVal.innerText = memPctStr;
  306. const sideRamBar = document.getElementById('side-ram-bar');
  307. if (sideRamBar) sideRamBar.style.width = memWidth;
  308. // Dashboard RAM Card
  309. const dashRamVal = document.getElementById('dash-ram-val');
  310. if (dashRamVal) dashRamVal.innerText = memPctStr;
  311. const dashRamBar = document.getElementById('dash-ram-bar');
  312. if (dashRamBar) {
  313. dashRamBar.style.width = memWidth;
  314. if (memPct > 85) {
  315. dashRamBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  316. } else if (memPct > 70) {
  317. dashRamBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  318. } else {
  319. dashRamBar.className = 'h-full rounded-full bg-indigo-500 transition-all duration-500';
  320. }
  321. }
  322. const dashRamUsedTotal = document.getElementById('dash-ram-used-total');
  323. if (dashRamUsedTotal) {
  324. dashRamUsedTotal.innerText = `${fmtMemMB(usedMB)} / ${fmtMemMB(totalMB)}`;
  325. }
  326. const dashRamFree = document.getElementById('dash-ram-free');
  327. if (dashRamFree) {
  328. dashRamFree.innerText = fmtMemMB(freeMB);
  329. }
  330. const dashRamStatus = document.getElementById('dash-ram-status');
  331. if (dashRamStatus) {
  332. if (memPct > 85) {
  333. dashRamStatus.innerText = 'High';
  334. dashRamStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  335. } else {
  336. dashRamStatus.innerText = 'Active';
  337. dashRamStatus.className = 'text-[11px] font-semibold text-indigo-400 uppercase px-2 py-0.5 rounded bg-indigo-500/10';
  338. }
  339. }
  340. // Legacy Dashboard Stats (Safe checks)
  341. const elIfacesUp = document.getElementById('stat-ifaces-up');
  342. if (elIfacesUp) elIfacesUp.innerText = s.up_ifaces || 0;
  343. const elIfacesTot = document.getElementById('stat-ifaces-total');
  344. if (elIfacesTot) elIfacesTot.innerText = `${s.total_ifaces || 0} Total`;
  345. const elIfacesDown = document.getElementById('stat-ifaces-down');
  346. if (elIfacesDown) elIfacesDown.innerText = `${s.down_ifaces || 0} DOWN`;
  347. const elVlans = document.getElementById('stat-vlans-count');
  348. if (elVlans) elVlans.innerText = s.vlan_ifaces || 0;
  349. // VPN Status Indicators
  350. if (v) {
  351. const totalActive = v.total_active_tunnels || 0;
  352. const statVpnActive = document.getElementById('stat-vpn-active');
  353. if (statVpnActive) statVpnActive.innerText = totalActive;
  354. const tunnelsDot = document.getElementById('tunnels-dot');
  355. const tunnelsLabel = document.getElementById('tunnels-label');
  356. if (tunnelsDot && tunnelsLabel) {
  357. if (totalActive > 0) {
  358. tunnelsDot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  359. tunnelsLabel.innerText = `${totalActive} Active VPN Tunnel${totalActive > 1 ? 's' : ''}`;
  360. } else {
  361. tunnelsDot.className = 'w-2 h-2 rounded-full bg-slate-500';
  362. tunnelsLabel.innerText = '0 Active VPN Tunnels';
  363. }
  364. }
  365. setDotBadge('badge-pppoe-status', (v.active_pppoe || 0) > 0 || v.pppoe_connected);
  366. setDotBadge('badge-wg-status', (v.active_wireguard || 0) > 0 || v.wireguard_active);
  367. setDotBadge('badge-ipsec-status', (v.active_ipsec || 0) > 0 || v.ipsec_active);
  368. setDotBadge('badge-l2tp-status', (v.active_l2tp || 0) > 0 || v.l2tp_connected);
  369. setDotBadge('badge-pptp-status', (v.active_pptp || 0) > 0 || v.pptp_connected);
  370. }
  371. // Total Live Bandwidth Rate
  372. let totalRx = 0;
  373. let totalTx = 0;
  374. (state.interfaces || []).forEach(i => {
  375. if (i.rate) {
  376. totalRx += i.rate.rx_bytes_sec || 0;
  377. totalTx += i.rate.tx_bytes_sec || 0;
  378. }
  379. });
  380. document.getElementById('stat-traffic-rx').innerText = formatTraffic(totalRx);
  381. document.getElementById('stat-traffic-tx').innerText = formatTraffic(totalTx);
  382. }
  383. function setDotBadge(id, active) {
  384. const el = document.getElementById(id);
  385. if (!el) return;
  386. if (active) {
  387. el.className = 'w-2 h-2 rounded-full bg-emerald-400 shadow-sm shadow-emerald-400/80';
  388. } else {
  389. el.className = 'w-2 h-2 rounded-full bg-slate-600';
  390. }
  391. }
  392. function updateBadges() {
  393. const bIfaces = document.getElementById('badge-ifaces-count');
  394. if (bIfaces) bIfaces.innerText = (state.interfaces || []).length;
  395. const bVlans = document.getElementById('badge-vlans-count');
  396. if (bVlans) bVlans.innerText = (state.vlans || []).length;
  397. if (state.fwSummary) {
  398. const totalFwRules = (state.fwSummary.filter_rules_count || 0) + (state.fwSummary.nat_rules_count || 0) + (state.fwSummary.mangle_rules_count || 0);
  399. const badgeFw = document.getElementById('badge-firewall-count');
  400. if (badgeFw) badgeFw.innerText = totalFwRules;
  401. }
  402. if (state.vpnStatus) {
  403. const v = state.vpnStatus;
  404. const bEoIP = document.getElementById('badge-eoip-count');
  405. if (bEoIP) bEoIP.innerText = v.total_eoip || 0;
  406. const bPPPSess = document.getElementById('badge-ppp-sessions');
  407. if (bPPPSess) bPPPSess.innerText = v.total_ppp_sessions || 0;
  408. setDotBadge('badge-pppoe-status', v.active_pppoe > 0 || v.pppoe_server_running);
  409. setDotBadge('badge-wg-status', v.active_wireguard > 0);
  410. setDotBadge('badge-ipsec-status', v.active_ipsec > 0 || v.ipsec_server_running);
  411. setDotBadge('badge-l2tp-status', v.active_l2tp > 0 || v.l2tp_server_running);
  412. setDotBadge('badge-pptp-status', v.active_pptp > 0 || v.pptp_server_running);
  413. }
  414. if (state.dynSummary) {
  415. const d = state.dynSummary;
  416. setDotBadge('badge-bgp-dot', d.bgp_running);
  417. setDotBadge('badge-ospf-dot', d.ospf_running);
  418. const bBgp = document.getElementById('badge-bgp-count');
  419. if (bBgp) bBgp.innerText = (state.bgpPeers || []).length;
  420. const bOspf = document.getElementById('badge-ospf-count');
  421. if (bOspf) bOspf.innerText = (state.ospfInterfaces || []).length;
  422. const bFilters = document.getElementById('badge-filters-count');
  423. if (bFilters) bFilters.innerText = (state.routingFilters || []).length;
  424. }
  425. }
  426. // Render Dashboard View
  427. function renderDashboard() {
  428. const matrix = document.getElementById('port-matrix');
  429. matrix.innerHTML = '';
  430. (state.interfaces || []).forEach(iface => {
  431. const isUp = iface.state === 'UP';
  432. const isVlan = iface.is_vlan;
  433. const portCard = document.createElement('div');
  434. portCard.className = `p-3 rounded-xl border transition-all cursor-pointer select-none group ${
  435. isUp
  436. ? (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')
  437. : 'bg-slate-900/40 border-slate-800/60 opacity-60 hover:opacity-100 hover:border-slate-700'
  438. }`;
  439. portCard.onclick = () => openIfaceModal(iface.name);
  440. let statusPillClass = isUp ? 'bg-emerald-500 shadow-sm shadow-emerald-500/50' : 'bg-rose-500';
  441. if (isVlan) statusPillClass = isUp ? 'bg-cyan-400 shadow-sm shadow-cyan-400/50' : 'bg-rose-500';
  442. portCard.innerHTML = `
  443. <div class="flex items-center justify-between mb-2">
  444. <span class="font-bold text-xs font-mono text-white group-hover:text-brand-400 transition truncate">${iface.name}</span>
  445. <span class="w-2 h-2 rounded-full ${statusPillClass}"></span>
  446. </div>
  447. <div class="text-[11px] font-mono text-slate-300 truncate">${iface.ipv4 && iface.ipv4.length > 0 ? iface.ipv4[0] : (iface.mac || 'No IP')}</div>
  448. <div class="mt-2 flex items-center justify-between text-[10px] text-slate-400">
  449. <span class="uppercase tracking-wider font-semibold">${isVlan ? `VLAN ${iface.vlan_id}` : iface.type}</span>
  450. <span>${iface.rate?.rx_human || '0 B/s'}</span>
  451. </div>
  452. `;
  453. matrix.appendChild(portCard);
  454. });
  455. const ifaceTbody = document.getElementById('quick-interfaces-table');
  456. if (ifaceTbody) {
  457. ifaceTbody.innerHTML = '';
  458. (state.interfaces || []).forEach(i => {
  459. const isUp = i.state === 'UP';
  460. const tr = document.createElement('tr');
  461. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  462. tr.onclick = () => openIfaceModal(i.name);
  463. const rxStr = i.rate?.rx_human || '0 B/s';
  464. const txStr = i.rate?.tx_human || '0 B/s';
  465. tr.innerHTML = `
  466. <td class="py-2.5 font-bold text-white flex items-center gap-2">
  467. <span class="w-2 h-2 rounded-full ${isUp ? 'bg-emerald-400 shadow-sm shadow-emerald-400/50' : 'bg-rose-400'}"></span>
  468. <span>${i.name}</span>
  469. </td>
  470. <td class="py-2.5 text-slate-300 font-sans">
  471. <span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 font-medium">${i.role || i.type || 'Ethernet'}</span>
  472. </td>
  473. <td class="py-2.5 text-slate-400 text-[11px] font-mono">${i.mac || '-'}</td>
  474. <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>
  475. <td class="py-2.5 text-slate-300 text-[11px] font-mono">
  476. <span class="text-emerald-400">↓ ${rxStr}</span> <span class="text-slate-600">•</span> <span class="text-cyan-400">↑ ${txStr}</span>
  477. </td>
  478. <td class="py-2.5 text-right font-sans font-semibold">
  479. <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>
  480. </td>
  481. `;
  482. ifaceTbody.appendChild(tr);
  483. });
  484. }
  485. const vlanTbody = document.getElementById('quick-vlans-table');
  486. if (vlanTbody) {
  487. vlanTbody.innerHTML = '';
  488. }
  489. }
  490. // Expand / Collapse Handlers
  491. function toggleExpand(parentName) {
  492. if (state.expandedParents.has(parentName)) {
  493. state.expandedParents.delete(parentName);
  494. } else {
  495. state.expandedParents.add(parentName);
  496. }
  497. renderInterfacesList();
  498. }
  499. // VLAN Support Checker: 802.1Q sub-interfaces are only supported on physical ethernet, veth, bridge, bond
  500. function supportsVLAN(iface) {
  501. if (!iface) return false;
  502. if (iface.is_vlan) return false;
  503. const name = (iface.name || '').toLowerCase();
  504. const type = (iface.type || '').toLowerCase();
  505. const role = (iface.role || '').toLowerCase();
  506. // Exclude loopback
  507. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  508. // Exclude WireGuard (Layer 3 tunnel, no 802.1Q support)
  509. if (type === 'wireguard' || name.startsWith('wg')) return false;
  510. // Exclude PPP / PPPoE
  511. if (type === 'ppp' || name.startsWith('ppp')) return false;
  512. // Exclude other Layer 3 tunnels and dummy devices
  513. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  514. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  515. return false;
  516. }
  517. // If name already contains a dot, it's already a sub-interface
  518. if (name.includes('.')) return false;
  519. return true;
  520. }
  521. // Expand / Collapse Handlers
  522. function toggleExpand(parentName) {
  523. const childVlans = (state.vlans || []).filter(v => v.parent_name === parentName || v.name.startsWith(parentName + '.'));
  524. if (childVlans.length === 0) {
  525. // Cannot expand an interface with no VLANs
  526. state.expandedParents.delete(parentName);
  527. return;
  528. }
  529. if (state.expandedParents.has(parentName)) {
  530. state.expandedParents.delete(parentName);
  531. } else {
  532. state.expandedParents.add(parentName);
  533. }
  534. renderInterfacesList();
  535. }
  536. function expandAllIfaces(expand) {
  537. if (expand) {
  538. (state.interfaces || []).forEach(i => {
  539. const hasVlans = (state.vlans || []).some(v => v.parent_name === i.name || v.name.startsWith(i.name + '.'));
  540. if (!i.is_vlan && hasVlans) state.expandedParents.add(i.name);
  541. });
  542. } else {
  543. state.expandedParents.clear();
  544. }
  545. renderInterfacesList();
  546. }
  547. // Filter and Render Hierarchical Interfaces List
  548. function filterIfaces(filter) {
  549. state.ifaceFilter = filter || 'all';
  550. renderInterfacesList();
  551. }
  552. function renderInterfacesList() {
  553. const tbody = document.getElementById('interfaces-tree-tbody');
  554. const emptyState = document.getElementById('interfaces-empty-state');
  555. const summary = document.getElementById('ifaces-list-summary');
  556. const query = (document.getElementById('iface-search')?.value || '').trim().toLowerCase();
  557. tbody.innerHTML = '';
  558. const allIfaces = state.interfaces || [];
  559. const allVlans = state.vlans || [];
  560. const parentIfaces = allIfaces.filter(i => !i.is_vlan);
  561. const filteredParents = parentIfaces.filter(parent => {
  562. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  563. if (query) {
  564. const matchName = parent.name.toLowerCase().includes(query);
  565. const matchIp = (parent.ipv4 || []).some(ip => ip.toLowerCase().includes(query));
  566. const matchRole = (parent.role || '').toLowerCase().includes(query);
  567. const matchType = (parent.type || '').toLowerCase().includes(query);
  568. const matchVlan = childVlans.some(v =>
  569. v.name.toLowerCase().includes(query) ||
  570. String(v.vlan_id).includes(query) ||
  571. (v.ipv4 || []).some(ip => ip.toLowerCase().includes(query)) ||
  572. (v.description || '').toLowerCase().includes(query)
  573. );
  574. if (!matchName && !matchIp && !matchRole && !matchType && !matchVlan) return false;
  575. }
  576. if (state.ifaceFilter === 'has_vlans') return childVlans.length > 0;
  577. if (state.ifaceFilter === 'physical') return parent.type !== 'loopback';
  578. if (state.ifaceFilter === 'up') return parent.state === 'UP';
  579. return true;
  580. });
  581. if (summary) {
  582. summary.innerText = `${parentIfaces.length} Interfaces • ${allVlans.length} Active VLANs`;
  583. }
  584. if (filteredParents.length === 0) {
  585. emptyState?.classList.remove('hidden');
  586. return;
  587. }
  588. emptyState?.classList.add('hidden');
  589. filteredParents.forEach(parent => {
  590. const isUp = parent.state === 'UP';
  591. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  592. const hasVlans = childVlans.length > 0;
  593. const isExpanded = hasVlans && state.expandedParents.has(parent.name);
  594. const canHaveVlan = supportsVLAN(parent);
  595. const parentRow = document.createElement('tr');
  596. parentRow.className = `hover:bg-slate-800/50 transition border-b border-slate-800/80 ${isExpanded ? 'bg-slate-900/80' : ''}`;
  597. parentRow.innerHTML = `
  598. <td class="py-3 px-3 text-center">
  599. ${hasVlans ? `
  600. <button onclick="toggleExpand('${parent.name}')" title="${isExpanded ? 'Collapse VLANs' : 'Expand VLANs'}"
  601. class="w-6 h-6 rounded flex items-center justify-center hover:bg-slate-800 text-slate-400 hover:text-white transition">
  602. <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">
  603. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M9 5l7 7-7 7" />
  604. </svg>
  605. </button>
  606. ` : `
  607. <div class="w-6 h-6 flex items-center justify-center text-slate-700 select-none">
  608. <span class="w-1.5 h-1.5 rounded-full bg-slate-800"></span>
  609. </div>
  610. `}
  611. </td>
  612. <td class="py-3 px-4">
  613. <div class="flex items-center space-x-2.5">
  614. <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">
  615. ${parent.type === 'loopback' ? 'LO' : (parent.type === 'wireguard' ? 'WG' : (parent.type === 'bridge' ? 'BR' : 'NIC'))}
  616. </div>
  617. <div>
  618. <div class="flex items-center gap-2">
  619. ${hasVlans ? `
  620. <span class="font-bold text-white text-sm cursor-pointer hover:text-cyan-400" onclick="toggleExpand('${parent.name}')">${parent.name}</span>
  621. <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>
  622. ` : `
  623. <span class="font-bold text-white text-sm">${parent.name}</span>
  624. <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>
  625. `}
  626. </div>
  627. <div class="text-[10px] text-slate-500 font-sans mt-0.5">${parent.type}</div>
  628. </div>
  629. </div>
  630. </td>
  631. <td class="py-3 px-4 font-sans">
  632. <div class="flex items-center gap-1.5">
  633. <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>
  634. <span class="text-xs text-slate-400 truncate max-w-[120px]">${parent.description || '-'}</span>
  635. </div>
  636. </td>
  637. <td class="py-3 px-4">
  638. ${parent.ipv4 && parent.ipv4.length > 0
  639. ? `<div class="text-white font-medium">${parent.ipv4[0]}</div>`
  640. : '<span class="text-slate-600 font-sans">Unassigned</span>'
  641. }
  642. ${(() => {
  643. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  644. if (!c) return '';
  645. 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');
  646. 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>`;
  647. })()}
  648. </td>
  649. <td class="py-3 px-4 text-slate-400 text-[11px]">
  650. <div>${parent.mac || 'N/A'}</div>
  651. <div class="text-[10px] text-slate-500">MTU ${parent.mtu}</div>
  652. </td>
  653. <td class="py-3 px-4 text-[11px]">
  654. <div class="flex items-center space-x-2">
  655. <span class="text-emerald-400">↓ ${parent.rate?.rx_human || '0 B/s'}</span>
  656. <span class="text-cyan-400">↑ ${parent.rate?.tx_human || '0 B/s'}</span>
  657. </div>
  658. </td>
  659. <td class="py-3 px-4 font-sans">
  660. <button onclick="toggleInterfaceState('${parent.name}', '${isUp ? 'down' : 'up'}')"
  661. class="flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full transition ${
  662. 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'
  663. }" title="Click to toggle link status">
  664. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  665. <span>${parent.state}</span>
  666. </button>
  667. </td>
  668. <td class="py-3 px-4 text-right space-x-2 font-sans">
  669. ${(() => {
  670. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  671. if (c) {
  672. 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>`;
  673. }
  674. 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>`;
  675. })()}
  676. ${canHaveVlan ? `
  677. <button onclick="openVlanModal('${parent.name}')"
  678. 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">
  679. + Add VLAN
  680. </button>
  681. ` : ''}
  682. <button onclick="openIfaceModal('${parent.name}')"
  683. 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">
  684. Configure
  685. </button>
  686. </td>
  687. `;
  688. tbody.appendChild(parentRow);
  689. if (isExpanded) {
  690. const drawerRow = document.createElement('tr');
  691. drawerRow.className = 'bg-slate-950/80 border-b border-slate-800/90';
  692. const drawerCell = document.createElement('td');
  693. drawerCell.colSpan = 8;
  694. drawerCell.className = 'p-0';
  695. drawerCell.innerHTML = `
  696. <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">
  697. <div class="flex items-center justify-between mb-3">
  698. <div class="flex items-center space-x-3">
  699. <span class="font-bold text-xs text-white uppercase tracking-wider flex items-center gap-1.5 font-sans">
  700. <span>VLAN Sub-interfaces on <code class="text-cyan-300 lowercase">${parent.name}</code></span>
  701. </span>
  702. <span class="text-[11px] bg-cyan-950 text-cyan-400 px-2 py-0.5 rounded-full border border-cyan-800/60 font-mono">
  703. ${childVlans.length} Attached
  704. </span>
  705. </div>
  706. <button onclick="openVlanModal('${parent.name}')"
  707. 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">
  708. <span>+ Create VLAN on ${parent.name}</span>
  709. </button>
  710. </div>
  711. ${childVlans.length === 0 ? `
  712. <div class="p-6 text-center border border-dashed border-slate-800 rounded-xl bg-slate-900/40 font-sans">
  713. <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>
  714. <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">
  715. <span>+ Create Your First VLAN on ${parent.name}</span>
  716. </button>
  717. </div>
  718. ` : `
  719. <div class="overflow-x-auto rounded-lg border border-slate-800 bg-slate-900/90 shadow-inner">
  720. <table class="w-full text-left text-xs font-mono">
  721. <thead class="text-slate-400 bg-slate-950/70 border-b border-slate-800 uppercase tracking-wider text-[10px] font-sans">
  722. <tr>
  723. <th class="py-2.5 px-4">VLAN ID</th>
  724. <th class="py-2.5 px-4">Interface Device</th>
  725. <th class="py-2.5 px-4">Subnet Gateway</th>
  726. <th class="py-2.5 px-4">Role / Alias</th>
  727. <th class="py-2.5 px-4">MTU</th>
  728. <th class="py-2.5 px-4">Throughput</th>
  729. <th class="py-2.5 px-4">Status</th>
  730. <th class="py-2.5 px-4 text-right">Actions</th>
  731. </tr>
  732. </thead>
  733. <tbody class="divide-y divide-slate-800/70">
  734. ${childVlans.map(v => {
  735. const isVlanUp = v.state === 'UP';
  736. return `
  737. <tr class="hover:bg-slate-800/40 transition">
  738. <td class="py-2.5 px-4">
  739. <span class="px-2 py-0.5 rounded text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800 shadow-sm">
  740. VLAN ${v.vlan_id}
  741. </span>
  742. </td>
  743. <td class="py-2.5 px-4 font-bold text-white flex items-center gap-1.5">
  744. <span class="text-cyan-500">└─</span>
  745. <span>${v.name}</span>
  746. </td>
  747. <td class="py-2.5 px-4 text-emerald-400 font-medium">
  748. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  749. ${(() => {
  750. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  751. if (!c) return '';
  752. 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';
  753. 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>`;
  754. })()}
  755. </td>
  756. <td class="py-2.5 px-4 font-sans text-slate-300">
  757. <span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 mr-1.5">${v.role || 'VLAN'}</span>
  758. <span class="text-slate-400 text-xs">${v.description || '-'}</span>
  759. </td>
  760. <td class="py-2.5 px-4 text-slate-400">${v.mtu}</td>
  761. <td class="py-2.5 px-4 text-[11px]">
  762. <span class="text-emerald-400">↓ ${v.rate?.rx_human || '0 B/s'}</span>
  763. <span class="text-cyan-400 ml-1.5">↑ ${v.rate?.tx_human || '0 B/s'}</span>
  764. </td>
  765. <td class="py-2.5 px-4 font-sans">
  766. <button onclick="toggleInterfaceState('${v.name}', '${isVlanUp ? 'down' : 'up'}')"
  767. class="flex items-center gap-1 text-[11px] font-semibold px-2 py-0.5 rounded-full ${
  768. 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'
  769. }">
  770. <span class="w-1.5 h-1.5 rounded-full ${isVlanUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  771. <span>${v.state}</span>
  772. </button>
  773. </td>
  774. <td class="py-2.5 px-4 text-right space-x-1.5 font-sans">
  775. ${(() => {
  776. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  777. if (c) {
  778. 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>`;
  779. }
  780. 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>`;
  781. })()}
  782. <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>
  783. <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>
  784. </td>
  785. </tr>
  786. `;
  787. }).join('')}
  788. </tbody>
  789. </table>
  790. </div>
  791. `}
  792. </div>
  793. `;
  794. drawerRow.appendChild(drawerCell);
  795. tbody.appendChild(drawerRow);
  796. }
  797. });
  798. }
  799. // Render VLANs Dedicated View
  800. function renderVlansList() {
  801. const tbody = document.getElementById('vlans-table-body');
  802. if (!tbody) return;
  803. const emptyState = document.getElementById('vlans-empty-state');
  804. const countBadge = document.getElementById('vlans-table-count');
  805. const query = (document.getElementById('vlan-search')?.value || '').toLowerCase();
  806. tbody.innerHTML = '';
  807. const allVlans = state.vlans || [];
  808. if (countBadge) countBadge.innerText = allVlans.length;
  809. const filtered = allVlans.filter(v => {
  810. if (!query) return true;
  811. return v.name.toLowerCase().includes(query) ||
  812. String(v.vlan_id).includes(query) ||
  813. (v.description || '').toLowerCase().includes(query) ||
  814. (v.ipv4 && v.ipv4.some(ip => ip.includes(query)));
  815. });
  816. if (allVlans.length === 0) {
  817. emptyState.classList.remove('hidden');
  818. return;
  819. }
  820. emptyState.classList.add('hidden');
  821. filtered.forEach(v => {
  822. const isUp = v.state === 'UP';
  823. const tr = document.createElement('tr');
  824. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  825. tr.innerHTML = `
  826. <td class="py-3 px-4">
  827. <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">
  828. VLAN ${v.vlan_id}
  829. </span>
  830. </td>
  831. <td class="py-3 px-4 font-bold text-white">${v.name}</td>
  832. <td class="py-3 px-4 text-slate-300">
  833. <span class="bg-slate-800 text-slate-200 px-2 py-0.5 rounded text-[11px]">${v.parent_name || 'eth0'}</span>
  834. </td>
  835. <td class="py-3 px-4 text-emerald-400 font-medium">
  836. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  837. </td>
  838. <td class="py-3 px-4 text-slate-300 font-sans">
  839. <span class="text-slate-400 text-xs">${v.description || v.role || '-'}</span>
  840. </td>
  841. <td class="py-3 px-4 text-slate-400">${v.mtu}</td>
  842. <td class="py-3 px-4 font-sans">
  843. <button onclick="toggleInterfaceState('${v.name}', '${isUp ? 'down' : 'up'}')"
  844. class="flex items-center gap-1.5 text-xs font-semibold px-2 py-0.5 rounded-full ${
  845. 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'
  846. }">
  847. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  848. <span>${v.state}</span>
  849. </button>
  850. </td>
  851. <td class="py-3 px-4 text-right space-x-2 font-sans">
  852. <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>
  853. <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>
  854. </td>
  855. `;
  856. tbody.appendChild(tr);
  857. });
  858. }
  859. // Toggle interface UP / DOWN
  860. async function toggleInterfaceState(name, newState) {
  861. try {
  862. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(name)}/state`, {
  863. method: 'POST',
  864. headers: { 'Content-Type': 'application/json' },
  865. body: JSON.stringify({ state: newState })
  866. });
  867. const data = await res.json();
  868. if (res.ok) {
  869. showToast('Interface Updated', `Interface ${name} is now ${newState.toUpperCase()}`, 'success');
  870. fetchData(false);
  871. } else {
  872. showToast('Error', data.message || 'Failed to toggle interface state', 'error');
  873. }
  874. } catch (err) {
  875. showToast('Error', err.message, 'error');
  876. }
  877. }
  878. // ---------------- MikroTik Flag & Utilities ----------------
  879. function renderMikroTikFlag(running, disabled) {
  880. if (running) {
  881. 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>`;
  882. }
  883. if (disabled) {
  884. 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>`;
  885. }
  886. 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>`;
  887. }
  888. function copyToClipboard(text, label = 'Text') {
  889. navigator.clipboard.writeText(text).then(() => {
  890. showToast('Copied', `${label} copied to clipboard`, 'success');
  891. }).catch(() => {
  892. prompt('Copy value:', text);
  893. });
  894. }
  895. // ======================== PPPoE Multi-Instance ========================
  896. async function loadPPPoE(populateInputs = true) {
  897. try {
  898. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`);
  899. const list = await res.json();
  900. state.pppoeList = Array.isArray(list) ? list : [];
  901. const badge = document.getElementById('pppoe-count-badge');
  902. if (badge) badge.innerText = `${state.pppoeList.length} Interface${state.pppoeList.length !== 1 ? 's' : ''}`;
  903. const tbody = document.getElementById('pppoe-table-body');
  904. const empty = document.getElementById('pppoe-empty');
  905. if (!tbody) return;
  906. tbody.innerHTML = '';
  907. if (state.pppoeList.length === 0) {
  908. if (empty) empty.classList.remove('hidden');
  909. } else {
  910. if (empty) empty.classList.add('hidden');
  911. state.pppoeList.forEach(inst => {
  912. const tr = document.createElement('tr');
  913. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  914. tr.innerHTML = `
  915. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  916. <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
  917. <td class="py-2.5 px-3 text-cyan-400 font-mono">${inst.interface}</td>
  918. <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
  919. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
  920. <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
  921. <td class="py-2.5 px-3 text-center">
  922. <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'}">
  923. ${inst.default_route ? 'Yes' : 'No'}
  924. </span>
  925. </td>
  926. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  927. ${inst.running ? `
  928. <button onclick="disconnectPPPoEInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  929. ` : `
  930. <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>
  931. `}
  932. <button onclick="togglePPPoEState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  933. ${inst.disabled ? 'Enable' : 'Disable'}
  934. </button>
  935. <button onclick="openEditPPPoEModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  936. <button onclick="deletePPPoEInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  937. </td>
  938. `;
  939. tbody.appendChild(tr);
  940. });
  941. }
  942. } catch (err) {
  943. console.error('Failed to load PPPoE:', err);
  944. }
  945. }
  946. function openAddPPPoEModal() {
  947. document.getElementById('pppoe-modal-title').innerText = 'Add PPPoE Client Interface';
  948. document.getElementById('pppoe-modal-edit-orig').value = '';
  949. document.getElementById('pppoe-modal-name').value = `pppoe-out${(state.pppoeList || []).length + 1}`;
  950. document.getElementById('pppoe-modal-name').readOnly = false;
  951. document.getElementById('pppoe-modal-user').value = '';
  952. document.getElementById('pppoe-modal-pass').value = '';
  953. document.getElementById('pppoe-modal-service').value = '';
  954. document.getElementById('pppoe-modal-mtu').value = '1492';
  955. document.getElementById('pppoe-modal-defroute').checked = true;
  956. document.getElementById('pppoe-modal-reconnect').checked = true;
  957. document.getElementById('pppoe-modal-disabled').checked = false;
  958. // Populate interfaces
  959. const sel = document.getElementById('pppoe-modal-iface');
  960. sel.innerHTML = '';
  961. (state.interfaces || []).forEach(i => {
  962. if (i.name === 'lo') return;
  963. const opt = document.createElement('option');
  964. opt.value = i.name;
  965. opt.innerText = `${i.name} (${i.role || i.type})`;
  966. sel.appendChild(opt);
  967. });
  968. document.getElementById('pppoe-modal').classList.remove('hidden');
  969. }
  970. function openEditPPPoEModal(name) {
  971. const inst = (state.pppoeList || []).find(i => i.name === name);
  972. if (!inst) return;
  973. document.getElementById('pppoe-modal-title').innerText = `Edit PPPoE Client: ${name}`;
  974. document.getElementById('pppoe-modal-edit-orig').value = name;
  975. document.getElementById('pppoe-modal-name').value = inst.name;
  976. document.getElementById('pppoe-modal-name').readOnly = true;
  977. document.getElementById('pppoe-modal-user').value = inst.username || '';
  978. document.getElementById('pppoe-modal-pass').value = inst.password || '';
  979. document.getElementById('pppoe-modal-service').value = inst.service_name || '';
  980. document.getElementById('pppoe-modal-mtu').value = inst.mtu || 1492;
  981. document.getElementById('pppoe-modal-defroute').checked = inst.default_route ?? true;
  982. document.getElementById('pppoe-modal-reconnect').checked = inst.auto_reconnect ?? true;
  983. document.getElementById('pppoe-modal-disabled').checked = !!inst.disabled;
  984. const sel = document.getElementById('pppoe-modal-iface');
  985. sel.innerHTML = '';
  986. (state.interfaces || []).forEach(i => {
  987. if (i.name === 'lo') return;
  988. const opt = document.createElement('option');
  989. opt.value = i.name;
  990. opt.innerText = `${i.name} (${i.role || i.type})`;
  991. if (i.name === inst.interface) opt.selected = true;
  992. sel.appendChild(opt);
  993. });
  994. document.getElementById('pppoe-modal').classList.remove('hidden');
  995. }
  996. function closePPPoEModal() {
  997. document.getElementById('pppoe-modal').classList.add('hidden');
  998. }
  999. async function submitSavePPPoE(e) {
  1000. e.preventDefault();
  1001. const name = document.getElementById('pppoe-modal-name').value.trim();
  1002. const iface = document.getElementById('pppoe-modal-iface').value;
  1003. const user = document.getElementById('pppoe-modal-user').value.trim();
  1004. const pass = document.getElementById('pppoe-modal-pass').value;
  1005. const service = document.getElementById('pppoe-modal-service').value.trim();
  1006. const mtu = parseInt(document.getElementById('pppoe-modal-mtu').value, 10) || 1492;
  1007. const defRoute = document.getElementById('pppoe-modal-defroute').checked;
  1008. const reconnect = document.getElementById('pppoe-modal-reconnect').checked;
  1009. const disabled = document.getElementById('pppoe-modal-disabled').checked;
  1010. try {
  1011. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`, {
  1012. method: 'POST',
  1013. headers: { 'Content-Type': 'application/json' },
  1014. body: JSON.stringify({
  1015. name,
  1016. interface: iface,
  1017. username: user,
  1018. password: pass,
  1019. service_name: service,
  1020. mtu,
  1021. default_route: defRoute,
  1022. auto_reconnect: reconnect,
  1023. disabled
  1024. })
  1025. });
  1026. if (res.ok) {
  1027. showToast('PPPoE Saved', `Configuration for ${name} saved`, 'success');
  1028. closePPPoEModal();
  1029. loadPPPoE(false);
  1030. fetchData(false);
  1031. } else {
  1032. const err = await res.json();
  1033. showToast('Error', err.message || 'Failed to save PPPoE', 'error');
  1034. }
  1035. } catch (err) {
  1036. showToast('Error', err.message, 'error');
  1037. }
  1038. }
  1039. async function connectPPPoEInstance(name) {
  1040. try {
  1041. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1042. if (res.ok) {
  1043. showToast('Connecting', `Dialing ${name}...`, 'info');
  1044. setTimeout(() => loadPPPoE(false), 2000);
  1045. }
  1046. } catch (err) {
  1047. showToast('Error', err.message, 'error');
  1048. }
  1049. }
  1050. async function disconnectPPPoEInstance(name) {
  1051. try {
  1052. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1053. if (res.ok) {
  1054. showToast('Disconnected', `${name} session terminated`, 'info');
  1055. setTimeout(() => loadPPPoE(false), 1000);
  1056. }
  1057. } catch (err) {
  1058. showToast('Error', err.message, 'error');
  1059. }
  1060. }
  1061. async function togglePPPoEState(name, enable) {
  1062. try {
  1063. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/state`, {
  1064. method: 'POST',
  1065. headers: { 'Content-Type': 'application/json' },
  1066. body: JSON.stringify({ enabled: enable })
  1067. });
  1068. if (res.ok) {
  1069. showToast(enable ? 'Enabled' : 'Disabled', `${name} is now ${enable ? 'enabled' : 'disabled'}`, 'info');
  1070. loadPPPoE(false);
  1071. }
  1072. } catch (err) {
  1073. showToast('Error', err.message, 'error');
  1074. }
  1075. }
  1076. async function deletePPPoEInstance(name) {
  1077. if (!confirm(`Are you sure you want to delete PPPoE client ${name}?`)) return;
  1078. try {
  1079. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1080. if (res.ok) {
  1081. showToast('Deleted', `PPPoE client ${name} removed`, 'success');
  1082. loadPPPoE(false);
  1083. fetchData(false);
  1084. }
  1085. } catch (err) {
  1086. showToast('Error', err.message, 'error');
  1087. }
  1088. }
  1089. // ======================== WireGuard Multi-Interface & Multi-Peer ========================
  1090. state.wgSubTab = 'ifaces';
  1091. function switchWGSubTab(tab) {
  1092. state.wgSubTab = tab;
  1093. const ifacesPanel = document.getElementById('wg-subtab-ifaces');
  1094. const peersPanel = document.getElementById('wg-subtab-peers');
  1095. const ifacesBtn = document.getElementById('wg-subtab-btn-ifaces');
  1096. const peersBtn = document.getElementById('wg-subtab-btn-peers');
  1097. if (tab === 'ifaces') {
  1098. ifacesPanel?.classList.remove('hidden');
  1099. peersPanel?.classList.add('hidden');
  1100. 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';
  1101. 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';
  1102. } else {
  1103. ifacesPanel?.classList.add('hidden');
  1104. peersPanel?.classList.remove('hidden');
  1105. 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';
  1106. 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';
  1107. renderWGPeers();
  1108. }
  1109. }
  1110. async function loadWireGuard(populateInputs = true) {
  1111. try {
  1112. const [ifacesRes, peersRes] = await Promise.all([
  1113. fetch(`${API_BASE}/vpn/wireguard/interfaces`),
  1114. fetch(`${API_BASE}/vpn/wireguard/peers`)
  1115. ]);
  1116. const ifaces = ifacesRes.ok ? await ifacesRes.json() : [];
  1117. const peers = peersRes.ok ? await peersRes.json() : [];
  1118. state.wgInterfaces = Array.isArray(ifaces) ? ifaces : [];
  1119. state.wgPeers = Array.isArray(peers) ? peers : [];
  1120. // Badges
  1121. const ifacesCountBadge = document.getElementById('wg-ifaces-count');
  1122. if (ifacesCountBadge) ifacesCountBadge.innerText = `${state.wgInterfaces.length} Interfaces`;
  1123. const peersCountBadge = document.getElementById('wg-peers-count');
  1124. if (peersCountBadge) peersCountBadge.innerText = `${state.wgPeers.length} Peers`;
  1125. const subTabIfaces = document.getElementById('wg-subtab-badge-ifaces');
  1126. if (subTabIfaces) subTabIfaces.innerText = state.wgInterfaces.length;
  1127. const subTabPeers = document.getElementById('wg-subtab-badge-peers');
  1128. if (subTabPeers) subTabPeers.innerText = state.wgPeers.length;
  1129. // Render Interfaces
  1130. const ifacesTbody = document.getElementById('wg-ifaces-table-body');
  1131. const ifacesEmpty = document.getElementById('wg-ifaces-empty');
  1132. if (ifacesTbody) {
  1133. ifacesTbody.innerHTML = '';
  1134. if (state.wgInterfaces.length === 0) {
  1135. if (ifacesEmpty) ifacesEmpty.classList.remove('hidden');
  1136. } else {
  1137. if (ifacesEmpty) ifacesEmpty.classList.add('hidden');
  1138. state.wgInterfaces.forEach(iface => {
  1139. const peersOnIface = state.wgPeers.filter(p => p.interface === iface.name).length;
  1140. const tr = document.createElement('tr');
  1141. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1142. tr.innerHTML = `
  1143. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(iface.running, iface.disabled)}</td>
  1144. <td class="py-2.5 px-3">
  1145. <div class="flex items-center gap-1.5">
  1146. <span class="font-bold text-white">${escapeHtml(iface.name)}</span>
  1147. ${iface.comment ? `<span class="text-[10px] text-slate-400 font-sans italic">(${escapeHtml(iface.comment)})</span>` : ''}
  1148. </div>
  1149. </td>
  1150. <td class="py-2.5 px-3 text-amber-400 font-mono">${iface.listen_port}</td>
  1151. <td class="py-2.5 px-3 text-emerald-400 font-mono">${iface.address || '<span class="text-slate-600 font-sans">--</span>'}</td>
  1152. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1153. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${iface.public_key}', 'Public Key')" title="Click to copy: ${iface.public_key}">
  1154. ${(iface.public_key || '').substring(0, 10)}... 📋
  1155. </span>
  1156. </td>
  1157. <td class="py-2.5 px-3 text-slate-400 font-mono">${iface.mtu || 1420}</td>
  1158. <td class="py-2.5 px-3 text-center">
  1159. <span class="px-2 py-0.5 rounded text-[10px] font-sans bg-slate-800 text-slate-300">${peersOnIface} peer${peersOnIface !== 1 ? 's' : ''}</span>
  1160. </td>
  1161. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  1162. ${iface.running ? `
  1163. <button onclick="stopWGInterface('${iface.name}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Stop</button>
  1164. ` : `
  1165. <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>
  1166. `}
  1167. <button onclick="toggleWGInterfaceState('${iface.name}', ${iface.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white font-medium">
  1168. ${iface.disabled ? 'Enable' : 'Disable'}
  1169. </button>
  1170. <button onclick="openEditWGInterfaceModal('${iface.name}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1171. <button onclick="deleteWGInterface('${iface.name}')" class="text-xs text-slate-500 hover:text-rose-400 font-medium">Delete</button>
  1172. </td>
  1173. `;
  1174. ifacesTbody.appendChild(tr);
  1175. });
  1176. }
  1177. }
  1178. // Populate filter dropdown in peers tab
  1179. const filterSel = document.getElementById('wg-peers-filter-iface');
  1180. if (filterSel) {
  1181. const currentVal = filterSel.value;
  1182. filterSel.innerHTML = '<option value="">All Interfaces</option>';
  1183. state.wgInterfaces.forEach(i => {
  1184. const opt = document.createElement('option');
  1185. opt.value = i.name;
  1186. opt.innerText = i.name;
  1187. if (i.name === currentVal) opt.selected = true;
  1188. filterSel.appendChild(opt);
  1189. });
  1190. }
  1191. renderWGPeers();
  1192. } catch (err) {
  1193. console.error('Failed to load WireGuard:', err);
  1194. }
  1195. }
  1196. function renderWGPeers() {
  1197. const filterSel = document.getElementById('wg-peers-filter-iface');
  1198. const selectedIface = filterSel ? filterSel.value : '';
  1199. const tbody = document.getElementById('wg-peers-table-body');
  1200. const empty = document.getElementById('wg-peers-empty');
  1201. if (!tbody) return;
  1202. tbody.innerHTML = '';
  1203. const filtered = selectedIface ? state.wgPeers.filter(p => p.interface === selectedIface) : state.wgPeers;
  1204. if (filtered.length === 0) {
  1205. if (empty) empty.classList.remove('hidden');
  1206. } else {
  1207. if (empty) empty.classList.add('hidden');
  1208. filtered.forEach(p => {
  1209. const isOnline = p.latest_handshake && !p.latest_handshake.includes('Never');
  1210. const tr = document.createElement('tr');
  1211. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1212. tr.innerHTML = `
  1213. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isOnline, p.disabled)}</td>
  1214. <td class="py-2.5 px-3 font-mono font-bold text-rose-400">${escapeHtml(p.interface)}</td>
  1215. <td class="py-2.5 px-3 font-bold text-white font-sans">${escapeHtml(p.name || 'Unnamed')}</td>
  1216. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1217. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${p.public_key}', 'Peer Public Key')" title="${p.public_key}">
  1218. ${(p.public_key || '').substring(0, 10)}... 📋
  1219. </span>
  1220. </td>
  1221. <td class="py-2.5 px-3 text-emerald-400 font-mono font-semibold">${(p.allowed_ips || []).join(', ')}</td>
  1222. <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>
  1223. <td class="py-2.5 px-3 text-slate-300 font-sans">${p.latest_handshake || 'Never'}</td>
  1224. <td class="py-2.5 px-3 font-mono text-[11px]">
  1225. <span class="text-emerald-400">↓ ${p.transfer_rx_human || '0 B'}</span>
  1226. <span class="text-cyan-400 ml-1">↑ ${p.transfer_tx_human || '0 B'}</span>
  1227. </td>
  1228. <td class="py-2.5 px-3 text-right font-sans space-x-2 whitespace-nowrap">
  1229. <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">
  1230. ${p.disabled ? 'Enable' : 'Disable'}
  1231. </button>
  1232. <button onclick="openEditWGPeerModal('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1233. <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>
  1234. <button onclick="deleteWGPeer('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Delete</button>
  1235. </td>
  1236. `;
  1237. tbody.appendChild(tr);
  1238. });
  1239. }
  1240. }
  1241. function openAddWGInterfaceModal() {
  1242. document.getElementById('wg-iface-modal-title').innerText = 'Add WireGuard Interface';
  1243. document.getElementById('wg-iface-modal-edit-orig').value = '';
  1244. const nameEl = document.getElementById('wg-iface-modal-name');
  1245. nameEl.value = `wg${(state.wgInterfaces || []).length}`;
  1246. nameEl.readOnly = false;
  1247. document.getElementById('wg-iface-modal-port').value = 51820 + (state.wgInterfaces || []).length;
  1248. document.getElementById('wg-iface-modal-addr').value = `10.${10 + (state.wgInterfaces || []).length}.0.1/24`;
  1249. document.getElementById('wg-iface-modal-mtu').value = '1420';
  1250. document.getElementById('wg-iface-modal-comment').value = '';
  1251. document.getElementById('wg-iface-modal-pubkey').value = '';
  1252. document.getElementById('wg-iface-modal-privkey').value = '';
  1253. document.getElementById('wg-iface-modal-disabled').checked = false;
  1254. generateWGInterfaceKeys();
  1255. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1256. }
  1257. function openEditWGInterfaceModal(name) {
  1258. const iface = (state.wgInterfaces || []).find(i => i.name === name);
  1259. if (!iface) return;
  1260. document.getElementById('wg-iface-modal-title').innerText = `Edit WireGuard Interface: ${name}`;
  1261. document.getElementById('wg-iface-modal-edit-orig').value = name;
  1262. const nameEl = document.getElementById('wg-iface-modal-name');
  1263. nameEl.value = iface.name;
  1264. nameEl.readOnly = false; // ALLOW RENAMING
  1265. document.getElementById('wg-iface-modal-port').value = iface.listen_port || 51820;
  1266. document.getElementById('wg-iface-modal-addr').value = iface.address || '';
  1267. document.getElementById('wg-iface-modal-mtu').value = iface.mtu || 1420;
  1268. document.getElementById('wg-iface-modal-comment').value = iface.comment || '';
  1269. document.getElementById('wg-iface-modal-pubkey').value = iface.public_key || '';
  1270. document.getElementById('wg-iface-modal-privkey').value = iface.private_key || '';
  1271. document.getElementById('wg-iface-modal-disabled').checked = !!iface.disabled;
  1272. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1273. }
  1274. function closeAddWGInterfaceModal() {
  1275. document.getElementById('wg-iface-modal').classList.add('hidden');
  1276. }
  1277. async function generateWGInterfaceKeys() {
  1278. try {
  1279. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1280. const keys = await res.json();
  1281. if (res.ok) {
  1282. document.getElementById('wg-iface-modal-privkey').value = keys.private_key;
  1283. document.getElementById('wg-iface-modal-pubkey').value = keys.public_key;
  1284. }
  1285. } catch (err) {
  1286. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1287. }
  1288. }
  1289. async function onWGInterfacePrivKeyInput() {
  1290. const privKey = document.getElementById('wg-iface-modal-privkey').value.trim();
  1291. if (!privKey) return;
  1292. try {
  1293. const res = await fetch(`${API_BASE}/vpn/wireguard/calc-pubkey`, {
  1294. method: 'POST',
  1295. headers: { 'Content-Type': 'application/json' },
  1296. body: JSON.stringify({ private_key: privKey })
  1297. });
  1298. if (res.ok) {
  1299. const data = await res.json();
  1300. if (data.public_key) {
  1301. document.getElementById('wg-iface-modal-pubkey').value = data.public_key;
  1302. }
  1303. }
  1304. } catch (err) {
  1305. // Ignore while typing
  1306. }
  1307. }
  1308. function toggleWGPrivKeyVisibility() {
  1309. const el = document.getElementById('wg-iface-modal-privkey');
  1310. const btn = document.getElementById('btn-toggle-wg-privkey');
  1311. if (el.type === 'password') {
  1312. el.type = 'text';
  1313. btn.innerText = '🙈 Hide';
  1314. } else {
  1315. el.type = 'password';
  1316. btn.innerText = '👁️ Show';
  1317. }
  1318. }
  1319. function copyWGInterfacePubKey() {
  1320. const pub = document.getElementById('wg-iface-modal-pubkey').value;
  1321. if (pub) copyToClipboard(pub, 'Interface Public Key');
  1322. }
  1323. async function submitSaveWGInterface(e) {
  1324. e.preventDefault();
  1325. const origName = document.getElementById('wg-iface-modal-edit-orig').value.trim();
  1326. const name = document.getElementById('wg-iface-modal-name').value.trim();
  1327. const port = parseInt(document.getElementById('wg-iface-modal-port').value, 10) || 51820;
  1328. const addr = document.getElementById('wg-iface-modal-addr').value.trim();
  1329. const mtu = parseInt(document.getElementById('wg-iface-modal-mtu').value, 10) || 1420;
  1330. const comment = document.getElementById('wg-iface-modal-comment').value.trim();
  1331. const pub = document.getElementById('wg-iface-modal-pubkey').value.trim();
  1332. const priv = document.getElementById('wg-iface-modal-privkey').value.trim();
  1333. const disabled = document.getElementById('wg-iface-modal-disabled').checked;
  1334. try {
  1335. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces`, {
  1336. method: 'POST',
  1337. headers: { 'Content-Type': 'application/json' },
  1338. body: JSON.stringify({
  1339. orig_name: origName,
  1340. name,
  1341. listen_port: port,
  1342. address: addr,
  1343. mtu,
  1344. comment,
  1345. public_key: pub,
  1346. private_key: priv,
  1347. disabled
  1348. })
  1349. });
  1350. const data = await res.json();
  1351. if (res.ok) {
  1352. showToast('WireGuard Saved', `Interface ${name} configured successfully`, 'success');
  1353. closeAddWGInterfaceModal();
  1354. loadWireGuard(false);
  1355. fetchData(false);
  1356. } else {
  1357. showToast('Error', data.error || 'Failed to save interface', 'error');
  1358. }
  1359. } catch (err) {
  1360. showToast('Error', err.message, 'error');
  1361. }
  1362. }
  1363. async function startWGInterface(name) {
  1364. try {
  1365. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1366. if (res.ok) {
  1367. showToast('Interface UP', `Started WireGuard interface ${name}`, 'success');
  1368. loadWireGuard(false);
  1369. fetchData(false);
  1370. }
  1371. } catch (err) {
  1372. showToast('Error', err.message, 'error');
  1373. }
  1374. }
  1375. async function stopWGInterface(name) {
  1376. try {
  1377. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1378. if (res.ok) {
  1379. showToast('Interface DOWN', `Stopped WireGuard interface ${name}`, 'info');
  1380. loadWireGuard(false);
  1381. fetchData(false);
  1382. }
  1383. } catch (err) {
  1384. showToast('Error', err.message, 'error');
  1385. }
  1386. }
  1387. async function toggleWGInterfaceState(name, enable) {
  1388. try {
  1389. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/state`, {
  1390. method: 'POST',
  1391. headers: { 'Content-Type': 'application/json' },
  1392. body: JSON.stringify({ enabled: enable })
  1393. });
  1394. if (res.ok) {
  1395. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1396. loadWireGuard(false);
  1397. fetchData(false);
  1398. }
  1399. } catch (err) {
  1400. showToast('Error', err.message, 'error');
  1401. }
  1402. }
  1403. async function deleteWGInterface(name) {
  1404. if (!confirm(`Are you sure you want to delete WireGuard interface ${name}? All associated peers will also be removed.`)) return;
  1405. try {
  1406. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1407. if (res.ok) {
  1408. showToast('Deleted', `Interface ${name} removed`, 'success');
  1409. loadWireGuard(false);
  1410. fetchData(false);
  1411. }
  1412. } catch (err) {
  1413. showToast('Error', err.message, 'error');
  1414. }
  1415. }
  1416. function populateWGPeerIfaceSelect(selectedIface = '') {
  1417. const sel = document.getElementById('wg-peer-modal-iface');
  1418. if (!sel) return;
  1419. sel.innerHTML = '';
  1420. (state.wgInterfaces || []).forEach(i => {
  1421. const opt = document.createElement('option');
  1422. opt.value = i.name;
  1423. opt.innerText = `${i.name} (${i.address || 'No IP'})`;
  1424. if (i.name === selectedIface) opt.selected = true;
  1425. sel.appendChild(opt);
  1426. });
  1427. }
  1428. function openAddWGPeerModal() {
  1429. if ((state.wgInterfaces || []).length === 0) {
  1430. showToast('No Interfaces', 'Please add a WireGuard interface first before adding peers', 'warning');
  1431. openAddWGInterfaceModal();
  1432. return;
  1433. }
  1434. document.getElementById('wg-peer-modal-title').innerText = 'Add WireGuard Peer';
  1435. document.getElementById('wg-peer-modal-edit-orig-iface').value = '';
  1436. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = '';
  1437. populateWGPeerIfaceSelect();
  1438. document.getElementById('wg-peer-modal-name').value = '';
  1439. document.getElementById('wg-peer-modal-pubkey').value = '';
  1440. document.getElementById('wg-peer-modal-allowedips').value = '10.10.0.2/32';
  1441. document.getElementById('wg-peer-modal-endpoint').value = '';
  1442. document.getElementById('wg-peer-modal-port').value = '';
  1443. document.getElementById('wg-peer-modal-keepalive').value = '25';
  1444. document.getElementById('wg-peer-modal-preshared').value = '';
  1445. document.getElementById('wg-peer-modal-disabled').checked = false;
  1446. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  1447. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  1448. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1449. }
  1450. function openEditWGPeerModal(ifaceName, pubKey) {
  1451. const peer = (state.wgPeers || []).find(p => p.interface === ifaceName && p.public_key === pubKey);
  1452. if (!peer) {
  1453. showToast('Not Found', 'Peer not found', 'warning');
  1454. return;
  1455. }
  1456. document.getElementById('wg-peer-modal-title').innerText = `Edit WireGuard Peer (${peer.name || ifaceName})`;
  1457. document.getElementById('wg-peer-modal-edit-orig-iface').value = peer.interface;
  1458. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = peer.public_key;
  1459. populateWGPeerIfaceSelect(peer.interface);
  1460. document.getElementById('wg-peer-modal-name').value = peer.name || '';
  1461. document.getElementById('wg-peer-modal-pubkey').value = peer.public_key || '';
  1462. document.getElementById('wg-peer-modal-allowedips').value = (peer.allowed_ips || []).join(', ');
  1463. document.getElementById('wg-peer-modal-endpoint').value = peer.endpoint_address || '';
  1464. document.getElementById('wg-peer-modal-port').value = peer.endpoint_port || '';
  1465. document.getElementById('wg-peer-modal-keepalive').value = peer.persistent_keepalive ?? 25;
  1466. document.getElementById('wg-peer-modal-preshared').value = peer.preshared_key || '';
  1467. document.getElementById('wg-peer-modal-disabled').checked = !!peer.disabled;
  1468. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  1469. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  1470. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1471. }
  1472. function closeAddWGPeerModal() {
  1473. document.getElementById('wg-peer-modal').classList.add('hidden');
  1474. }
  1475. async function generatePeerKeypairHelper() {
  1476. try {
  1477. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1478. const keys = await res.json();
  1479. if (res.ok) {
  1480. document.getElementById('wg-peer-modal-pubkey').value = keys.public_key;
  1481. document.getElementById('wg-peer-gen-privkey').value = keys.private_key;
  1482. document.getElementById('wg-peer-gen-key-box').classList.remove('hidden');
  1483. checkWGPeerKeyValidity();
  1484. showToast('Keypair Generated', 'Public key inserted and client private key ready to copy', 'info');
  1485. }
  1486. } catch (err) {
  1487. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1488. }
  1489. }
  1490. function copyGeneratedPeerPrivKey() {
  1491. const priv = document.getElementById('wg-peer-gen-privkey').value;
  1492. if (priv) copyToClipboard(priv, 'Client Private Key');
  1493. }
  1494. async function generatePeerPSK() {
  1495. try {
  1496. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1497. const keys = await res.json();
  1498. if (res.ok && keys.private_key) {
  1499. document.getElementById('wg-peer-modal-preshared').value = keys.private_key;
  1500. showToast('PSK Generated', 'Generated 256-bit preshared key', 'info');
  1501. }
  1502. } catch (err) {
  1503. showToast('Error', err.message, 'error');
  1504. }
  1505. }
  1506. function checkWGPeerKeyValidity() {
  1507. const ifaceName = document.getElementById('wg-peer-modal-iface').value;
  1508. const peerPubKey = document.getElementById('wg-peer-modal-pubkey').value.trim();
  1509. const warningEl = document.getElementById('wg-peer-key-warning');
  1510. if (!warningEl) return;
  1511. const targetIface = (state.wgInterfaces || []).find(i => i.name === ifaceName);
  1512. if (targetIface && targetIface.public_key && peerPubKey && targetIface.public_key === peerPubKey) {
  1513. warningEl.classList.remove('hidden');
  1514. } else {
  1515. warningEl.classList.add('hidden');
  1516. }
  1517. }
  1518. async function submitSaveWGPeer(e) {
  1519. e.preventDefault();
  1520. const origIface = document.getElementById('wg-peer-modal-edit-orig-iface').value.trim();
  1521. const origPubKey = document.getElementById('wg-peer-modal-edit-orig-pubkey').value.trim();
  1522. const iface = document.getElementById('wg-peer-modal-iface').value;
  1523. const name = document.getElementById('wg-peer-modal-name').value.trim();
  1524. const pub = document.getElementById('wg-peer-modal-pubkey').value.trim();
  1525. const allowed = document.getElementById('wg-peer-modal-allowedips').value
  1526. .split(',')
  1527. .map(s => s.trim())
  1528. .filter(s => s.length > 0);
  1529. const epHost = document.getElementById('wg-peer-modal-endpoint').value.trim();
  1530. const epPort = parseInt(document.getElementById('wg-peer-modal-port').value, 10) || 0;
  1531. const keepalive = parseInt(document.getElementById('wg-peer-modal-keepalive').value, 10) || 0;
  1532. const psk = document.getElementById('wg-peer-modal-preshared').value.trim();
  1533. const disabled = document.getElementById('wg-peer-modal-disabled').checked;
  1534. // Validation
  1535. const targetIface = (state.wgInterfaces || []).find(i => i.name === iface);
  1536. if (targetIface && targetIface.public_key === pub) {
  1537. showToast('Invalid Peer Key', 'Peer public key cannot be the same as the interface public key!', 'error');
  1538. return;
  1539. }
  1540. try {
  1541. const res = await fetch(`${API_BASE}/vpn/wireguard/peers`, {
  1542. method: 'POST',
  1543. headers: { 'Content-Type': 'application/json' },
  1544. body: JSON.stringify({
  1545. orig_interface: origIface,
  1546. orig_public_key: origPubKey,
  1547. interface: iface,
  1548. name,
  1549. public_key: pub,
  1550. allowed_ips: allowed,
  1551. endpoint_address: epHost,
  1552. endpoint_port: epPort,
  1553. persistent_keepalive: keepalive,
  1554. preshared_key: psk,
  1555. disabled
  1556. })
  1557. });
  1558. const data = await res.json();
  1559. if (res.ok) {
  1560. showToast('Peer Saved', `Peer ${name} saved on ${iface}`, 'success');
  1561. closeAddWGPeerModal();
  1562. loadWireGuard(false);
  1563. } else {
  1564. showToast('Error', data.error || 'Failed to save peer', 'error');
  1565. }
  1566. } catch (err) {
  1567. showToast('Error', err.message, 'error');
  1568. }
  1569. }
  1570. async function toggleWGPeerState(iface, pubkey, enable) {
  1571. try {
  1572. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/state`, {
  1573. method: 'POST',
  1574. headers: { 'Content-Type': 'application/json' },
  1575. body: JSON.stringify({ interface: iface, public_key: pubkey, enabled: enable })
  1576. });
  1577. const data = await res.json();
  1578. if (res.ok) {
  1579. showToast(enable ? 'Peer Enabled' : 'Peer Disabled', `Peer state updated on ${iface}`, 'info');
  1580. loadWireGuard(false);
  1581. } else {
  1582. showToast('Error', data.error || 'Failed to update peer state', 'error');
  1583. }
  1584. } catch (err) {
  1585. showToast('Error', err.message, 'error');
  1586. }
  1587. }
  1588. async function deleteWGPeer(iface, pubkey) {
  1589. if (!confirm(`Are you sure you want to remove peer from ${iface}?`)) return;
  1590. try {
  1591. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/delete`, {
  1592. method: 'POST',
  1593. headers: { 'Content-Type': 'application/json' },
  1594. body: JSON.stringify({ interface: iface, public_key: pubkey })
  1595. });
  1596. const data = await res.json();
  1597. if (res.ok) {
  1598. showToast('Peer Deleted', 'WireGuard peer removed', 'success');
  1599. loadWireGuard(false);
  1600. } else {
  1601. showToast('Error', data.error || 'Failed to remove peer', 'error');
  1602. }
  1603. } catch (err) {
  1604. showToast('Error', err.message, 'error');
  1605. }
  1606. }
  1607. // ======================== IPSec Multi-Tunnel ========================
  1608. async function loadIPSec(populateInputs = true) {
  1609. try {
  1610. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`);
  1611. const list = await res.json();
  1612. state.ipsecTunnels = Array.isArray(list) ? list : [];
  1613. const activeCount = state.ipsecTunnels.filter(t => t.running || t.status === 'ESTABLISHED').length;
  1614. const badge = document.getElementById('ipsec-sas-badge');
  1615. if (badge) badge.innerText = `${activeCount} Active SAs`;
  1616. const tbody = document.getElementById('ipsec-table-body');
  1617. const empty = document.getElementById('ipsec-empty');
  1618. if (!tbody) return;
  1619. tbody.innerHTML = '';
  1620. if (state.ipsecTunnels.length === 0) {
  1621. if (empty) empty.classList.remove('hidden');
  1622. } else {
  1623. if (empty) empty.classList.add('hidden');
  1624. state.ipsecTunnels.forEach(c => {
  1625. const isEstablished = c.running || c.status === 'ESTABLISHED';
  1626. const tr = document.createElement('tr');
  1627. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1628. tr.innerHTML = `
  1629. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isEstablished, c.disabled)}</td>
  1630. <td class="py-2.5 px-4 font-bold text-white">${c.name}</td>
  1631. <td class="py-2.5 px-4 text-emerald-400 font-mono">${c.local_subnet || '-'}</td>
  1632. <td class="py-2.5 px-4 text-slate-300 font-mono">${c.remote_addrs || '-'}</td>
  1633. <td class="py-2.5 px-4 text-cyan-400 font-mono">${c.remote_subnet || '-'}</td>
  1634. <td class="py-2.5 px-4 font-sans">
  1635. <span class="px-2 py-0.5 rounded-full text-[10px] font-semibold ${
  1636. isEstablished ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30' : 'bg-slate-800 text-slate-400'
  1637. }">${c.status || (isEstablished ? 'ESTABLISHED' : 'DISCONNECTED')}</span>
  1638. </td>
  1639. <td class="py-2.5 px-4 text-right space-x-2 font-sans">
  1640. ${isEstablished ? `
  1641. <button onclick="stopIPSecTunnel('${c.name}')" class="text-xs text-rose-400 hover:text-rose-300">Terminate</button>
  1642. ` : `
  1643. <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>
  1644. `}
  1645. <button onclick="toggleIPSecState('${c.name}', ${c.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1646. ${c.disabled ? 'Enable' : 'Disable'}
  1647. </button>
  1648. <button onclick="openEditIPSecModal('${c.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1649. <button onclick="deleteIPSecConn('${c.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1650. </td>
  1651. `;
  1652. tbody.appendChild(tr);
  1653. });
  1654. }
  1655. } catch (err) {
  1656. console.error('Failed to load IPSec:', err);
  1657. }
  1658. }
  1659. function openAddIPSecModal() {
  1660. document.getElementById('ipsec-modal-title').innerText = 'Configure IPSec IKEv2 Tunnel';
  1661. document.getElementById('ipsec-modal-name').value = `ipsec-${(state.ipsecTunnels || []).length + 1}`;
  1662. document.getElementById('ipsec-modal-name').readOnly = false;
  1663. document.getElementById('ipsec-modal-localts').value = '192.168.10.0/24';
  1664. document.getElementById('ipsec-modal-remotets').value = '192.168.20.0/24';
  1665. document.getElementById('ipsec-modal-remotegw').value = '';
  1666. document.getElementById('ipsec-modal-psk').value = '';
  1667. document.getElementById('ipsec-modal-ikeprop').value = 'aes256-sha256-modp2048,default';
  1668. document.getElementById('ipsec-modal-espprop').value = 'aes256-sha256-modp2048,default';
  1669. document.getElementById('ipsec-modal-autostart').checked = true;
  1670. document.getElementById('ipsec-modal-disabled').checked = false;
  1671. document.getElementById('ipsec-modal').classList.remove('hidden');
  1672. }
  1673. function openEditIPSecModal(name) {
  1674. const conn = (state.ipsecTunnels || []).find(c => c.name === name);
  1675. if (!conn) return;
  1676. document.getElementById('ipsec-modal-title').innerText = `Edit IPSec Tunnel: ${name}`;
  1677. document.getElementById('ipsec-modal-name').value = conn.name;
  1678. document.getElementById('ipsec-modal-name').readOnly = true;
  1679. document.getElementById('ipsec-modal-localts').value = conn.local_subnet || '';
  1680. document.getElementById('ipsec-modal-remotets').value = conn.remote_subnet || '';
  1681. document.getElementById('ipsec-modal-remotegw').value = conn.remote_addrs || '';
  1682. document.getElementById('ipsec-modal-psk').value = conn.preshared_key || '';
  1683. document.getElementById('ipsec-modal-ikeprop').value = conn.ike_proposals || 'aes256-sha256-modp2048,default';
  1684. document.getElementById('ipsec-modal-espprop').value = conn.esp_proposals || 'aes256-sha256-modp2048,default';
  1685. document.getElementById('ipsec-modal-autostart').checked = conn.auto_start ?? true;
  1686. document.getElementById('ipsec-modal-disabled').checked = !!conn.disabled;
  1687. document.getElementById('ipsec-modal').classList.remove('hidden');
  1688. }
  1689. function closeAddIPSecModal() {
  1690. document.getElementById('ipsec-modal').classList.add('hidden');
  1691. }
  1692. async function submitSaveIPSec(e) {
  1693. e.preventDefault();
  1694. const name = document.getElementById('ipsec-modal-name').value.trim();
  1695. const localts = document.getElementById('ipsec-modal-localts').value.trim();
  1696. const remotets = document.getElementById('ipsec-modal-remotets').value.trim();
  1697. const remotegw = document.getElementById('ipsec-modal-remotegw').value.trim();
  1698. const psk = document.getElementById('ipsec-modal-psk').value;
  1699. const ike = document.getElementById('ipsec-modal-ikeprop').value.trim();
  1700. const esp = document.getElementById('ipsec-modal-espprop').value.trim();
  1701. const autostart = document.getElementById('ipsec-modal-autostart').checked;
  1702. const disabled = document.getElementById('ipsec-modal-disabled').checked;
  1703. try {
  1704. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`, {
  1705. method: 'POST',
  1706. headers: { 'Content-Type': 'application/json' },
  1707. body: JSON.stringify({
  1708. name,
  1709. local_addrs: '%any',
  1710. remote_addrs: remotegw,
  1711. local_subnet: localts,
  1712. remote_subnet: remotets,
  1713. preshared_key: psk,
  1714. ike_proposals: ike,
  1715. esp_proposals: esp,
  1716. auto_start: autostart,
  1717. disabled
  1718. })
  1719. });
  1720. if (res.ok) {
  1721. showToast('IPSec Saved', `Tunnel ${name} configured`, 'success');
  1722. closeAddIPSecModal();
  1723. loadIPSec(false);
  1724. fetchData(false);
  1725. }
  1726. } catch (err) {
  1727. showToast('Error', err.message, 'error');
  1728. }
  1729. }
  1730. async function startIPSecTunnel(name) {
  1731. try {
  1732. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1733. if (res.ok) {
  1734. showToast('Initiating Tunnel', `Attempting SA handshake for ${name}...`, 'info');
  1735. setTimeout(() => loadIPSec(false), 2000);
  1736. }
  1737. } catch (err) {
  1738. showToast('Error', err.message, 'error');
  1739. }
  1740. }
  1741. async function stopIPSecTunnel(name) {
  1742. try {
  1743. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1744. if (res.ok) {
  1745. showToast('Terminated', `IPSec SA for ${name} closed`, 'info');
  1746. loadIPSec(false);
  1747. }
  1748. } catch (err) {
  1749. showToast('Error', err.message, 'error');
  1750. }
  1751. }
  1752. async function toggleIPSecState(name, enable) {
  1753. try {
  1754. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/state`, {
  1755. method: 'POST',
  1756. headers: { 'Content-Type': 'application/json' },
  1757. body: JSON.stringify({ enabled: enable })
  1758. });
  1759. if (res.ok) {
  1760. showToast(enable ? 'Enabled' : 'Disabled', `IPSec tunnel ${name} updated`, 'info');
  1761. loadIPSec(false);
  1762. }
  1763. } catch (err) {
  1764. showToast('Error', err.message, 'error');
  1765. }
  1766. }
  1767. async function deleteIPSecConn(name) {
  1768. if (!confirm(`Are you sure you want to delete IPSec tunnel ${name}?`)) return;
  1769. try {
  1770. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1771. if (res.ok) {
  1772. showToast('Deleted', `IPSec connection ${name} removed`, 'success');
  1773. loadIPSec(false);
  1774. fetchData(false);
  1775. }
  1776. } catch (err) {
  1777. showToast('Error', err.message, 'error');
  1778. }
  1779. }
  1780. // ======================== L2TP Multi-Instance ========================
  1781. async function loadL2TP(populateInputs = true) {
  1782. try {
  1783. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`);
  1784. const list = await res.json();
  1785. state.l2tpList = Array.isArray(list) ? list : [];
  1786. const badge = document.getElementById('l2tp-count-badge');
  1787. if (badge) badge.innerText = `${state.l2tpList.length} Client${state.l2tpList.length !== 1 ? 's' : ''}`;
  1788. const tbody = document.getElementById('l2tp-table-body');
  1789. const empty = document.getElementById('l2tp-empty');
  1790. if (!tbody) return;
  1791. tbody.innerHTML = '';
  1792. if (state.l2tpList.length === 0) {
  1793. if (empty) empty.classList.remove('hidden');
  1794. } else {
  1795. if (empty) empty.classList.add('hidden');
  1796. state.l2tpList.forEach(inst => {
  1797. const tr = document.createElement('tr');
  1798. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1799. tr.innerHTML = `
  1800. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1801. <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
  1802. <td class="py-2.5 px-3 text-cyan-400 font-mono">${inst.connect_to}</td>
  1803. <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
  1804. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
  1805. <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
  1806. <td class="py-2.5 px-3 text-center">
  1807. <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'}">
  1808. ${inst.default_route ? 'Yes' : 'No'}
  1809. </span>
  1810. </td>
  1811. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1812. ${inst.running ? `
  1813. <button onclick="disconnectL2TPInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1814. ` : `
  1815. <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>
  1816. `}
  1817. <button onclick="toggleL2TPState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1818. ${inst.disabled ? 'Enable' : 'Disable'}
  1819. </button>
  1820. <button onclick="openEditL2TPModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1821. <button onclick="deleteL2TPInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1822. </td>
  1823. `;
  1824. tbody.appendChild(tr);
  1825. });
  1826. }
  1827. } catch (err) {
  1828. console.error('Failed to load L2TP:', err);
  1829. }
  1830. }
  1831. function openAddL2TPModal() {
  1832. document.getElementById('l2tp-modal-title').innerText = 'Add L2TP Client Interface';
  1833. document.getElementById('l2tp-modal-name').value = `l2tp-out${(state.l2tpList || []).length + 1}`;
  1834. document.getElementById('l2tp-modal-name').readOnly = false;
  1835. document.getElementById('l2tp-modal-server').value = '';
  1836. document.getElementById('l2tp-modal-user').value = '';
  1837. document.getElementById('l2tp-modal-pass').value = '';
  1838. document.getElementById('l2tp-modal-ipsec').value = '';
  1839. document.getElementById('l2tp-modal-defroute').checked = true;
  1840. document.getElementById('l2tp-modal-disabled').checked = false;
  1841. document.getElementById('l2tp-modal').classList.remove('hidden');
  1842. }
  1843. function openEditL2TPModal(name) {
  1844. const inst = (state.l2tpList || []).find(i => i.name === name);
  1845. if (!inst) return;
  1846. document.getElementById('l2tp-modal-title').innerText = `Edit L2TP Client: ${name}`;
  1847. document.getElementById('l2tp-modal-name').value = inst.name;
  1848. document.getElementById('l2tp-modal-name').readOnly = true;
  1849. document.getElementById('l2tp-modal-server').value = inst.connect_to || '';
  1850. document.getElementById('l2tp-modal-user').value = inst.username || '';
  1851. document.getElementById('l2tp-modal-pass').value = inst.password || '';
  1852. document.getElementById('l2tp-modal-ipsec').value = inst.ipsec_secret || '';
  1853. document.getElementById('l2tp-modal-defroute').checked = inst.default_route ?? true;
  1854. document.getElementById('l2tp-modal-disabled').checked = !!inst.disabled;
  1855. document.getElementById('l2tp-modal').classList.remove('hidden');
  1856. }
  1857. function closeL2TPModal() {
  1858. document.getElementById('l2tp-modal').classList.add('hidden');
  1859. }
  1860. async function submitSaveL2TP(e) {
  1861. e.preventDefault();
  1862. const name = document.getElementById('l2tp-modal-name').value.trim();
  1863. const server = document.getElementById('l2tp-modal-server').value.trim();
  1864. const user = document.getElementById('l2tp-modal-user').value.trim();
  1865. const pass = document.getElementById('l2tp-modal-pass').value;
  1866. const ipsec = document.getElementById('l2tp-modal-ipsec').value;
  1867. const defRoute = document.getElementById('l2tp-modal-defroute').checked;
  1868. const disabled = document.getElementById('l2tp-modal-disabled').checked;
  1869. try {
  1870. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`, {
  1871. method: 'POST',
  1872. headers: { 'Content-Type': 'application/json' },
  1873. body: JSON.stringify({
  1874. name,
  1875. connect_to: server,
  1876. username: user,
  1877. password: pass,
  1878. ipsec_secret: ipsec,
  1879. default_route: defRoute,
  1880. disabled
  1881. })
  1882. });
  1883. if (res.ok) {
  1884. showToast('L2TP Saved', `Client ${name} configuration saved`, 'success');
  1885. closeL2TPModal();
  1886. loadL2TP(false);
  1887. fetchData(false);
  1888. }
  1889. } catch (err) {
  1890. showToast('Error', err.message, 'error');
  1891. }
  1892. }
  1893. async function connectL2TPInstance(name) {
  1894. try {
  1895. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1896. if (res.ok) {
  1897. showToast('Connecting', `Dialing L2TP ${name}...`, 'info');
  1898. setTimeout(() => loadL2TP(false), 2000);
  1899. }
  1900. } catch (err) {
  1901. showToast('Error', err.message, 'error');
  1902. }
  1903. }
  1904. async function disconnectL2TPInstance(name) {
  1905. try {
  1906. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1907. if (res.ok) {
  1908. showToast('Disconnected', `L2TP tunnel ${name} terminated`, 'info');
  1909. loadL2TP(false);
  1910. }
  1911. } catch (err) {
  1912. showToast('Error', err.message, 'error');
  1913. }
  1914. }
  1915. async function toggleL2TPState(name, enable) {
  1916. try {
  1917. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/state`, {
  1918. method: 'POST',
  1919. headers: { 'Content-Type': 'application/json' },
  1920. body: JSON.stringify({ enabled: enable })
  1921. });
  1922. if (res.ok) {
  1923. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1924. loadL2TP(false);
  1925. }
  1926. } catch (err) {
  1927. showToast('Error', err.message, 'error');
  1928. }
  1929. }
  1930. async function deleteL2TPInstance(name) {
  1931. if (!confirm(`Are you sure you want to delete L2TP client ${name}?`)) return;
  1932. try {
  1933. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1934. if (res.ok) {
  1935. showToast('Deleted', `L2TP client ${name} removed`, 'success');
  1936. loadL2TP(false);
  1937. fetchData(false);
  1938. }
  1939. } catch (err) {
  1940. showToast('Error', err.message, 'error');
  1941. }
  1942. }
  1943. // ======================== PPTP Multi-Instance ========================
  1944. async function loadPPTP(populateInputs = true) {
  1945. try {
  1946. const res = await fetch(`${API_BASE}/vpn/pptp/clients`);
  1947. const list = await res.json();
  1948. state.pptpList = Array.isArray(list) ? list : [];
  1949. const badge = document.getElementById('pptp-count-badge');
  1950. if (badge) badge.innerText = `${state.pptpList.length} Client${state.pptpList.length !== 1 ? 's' : ''}`;
  1951. const tbody = document.getElementById('pptp-table-body');
  1952. const empty = document.getElementById('pptp-empty');
  1953. if (!tbody) return;
  1954. tbody.innerHTML = '';
  1955. if (state.pptpList.length === 0) {
  1956. if (empty) empty.classList.remove('hidden');
  1957. } else {
  1958. if (empty) empty.classList.add('hidden');
  1959. state.pptpList.forEach(inst => {
  1960. const tr = document.createElement('tr');
  1961. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1962. tr.innerHTML = `
  1963. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1964. <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
  1965. <td class="py-2.5 px-3 text-purple-400 font-mono">${inst.connect_to}</td>
  1966. <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
  1967. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
  1968. <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
  1969. <td class="py-2.5 px-3 text-center">
  1970. <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'}">
  1971. ${inst.require_mppe ? 'MPPE-128' : 'None'}
  1972. </span>
  1973. </td>
  1974. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1975. ${inst.running ? `
  1976. <button onclick="disconnectPPTPInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1977. ` : `
  1978. <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>
  1979. `}
  1980. <button onclick="togglePPTPState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1981. ${inst.disabled ? 'Enable' : 'Disable'}
  1982. </button>
  1983. <button onclick="openEditPPTPModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1984. <button onclick="deletePPTPInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1985. </td>
  1986. `;
  1987. tbody.appendChild(tr);
  1988. });
  1989. }
  1990. } catch (err) {
  1991. console.error('Failed to load PPTP:', err);
  1992. }
  1993. }
  1994. function openAddPPTPModal() {
  1995. document.getElementById('pptp-modal-title').innerText = 'Add PPTP Client Interface';
  1996. document.getElementById('pptp-modal-name').value = `pptp-out${(state.pptpList || []).length + 1}`;
  1997. document.getElementById('pptp-modal-name').readOnly = false;
  1998. document.getElementById('pptp-modal-server').value = '';
  1999. document.getElementById('pptp-modal-user').value = '';
  2000. document.getElementById('pptp-modal-pass').value = '';
  2001. document.getElementById('pptp-modal-mppe').checked = true;
  2002. document.getElementById('pptp-modal-defroute').checked = true;
  2003. document.getElementById('pptp-modal-disabled').checked = false;
  2004. document.getElementById('pptp-modal').classList.remove('hidden');
  2005. }
  2006. function openEditPPTPModal(name) {
  2007. const inst = (state.pptpList || []).find(i => i.name === name);
  2008. if (!inst) return;
  2009. document.getElementById('pptp-modal-title').innerText = `Edit PPTP Client: ${name}`;
  2010. document.getElementById('pptp-modal-name').value = inst.name;
  2011. document.getElementById('pptp-modal-name').readOnly = true;
  2012. document.getElementById('pptp-modal-server').value = inst.connect_to || '';
  2013. document.getElementById('pptp-modal-user').value = inst.username || '';
  2014. document.getElementById('pptp-modal-pass').value = inst.password || '';
  2015. document.getElementById('pptp-modal-mppe').checked = inst.require_mppe ?? true;
  2016. document.getElementById('pptp-modal-defroute').checked = inst.default_route ?? true;
  2017. document.getElementById('pptp-modal-disabled').checked = !!inst.disabled;
  2018. document.getElementById('pptp-modal').classList.remove('hidden');
  2019. }
  2020. function closePPTPModal() {
  2021. document.getElementById('pptp-modal').classList.add('hidden');
  2022. }
  2023. async function submitSavePPTP(e) {
  2024. e.preventDefault();
  2025. const name = document.getElementById('pptp-modal-name').value.trim();
  2026. const server = document.getElementById('pptp-modal-server').value.trim();
  2027. const user = document.getElementById('pptp-modal-user').value.trim();
  2028. const pass = document.getElementById('pptp-modal-pass').value;
  2029. const mppe = document.getElementById('pptp-modal-mppe').checked;
  2030. const defRoute = document.getElementById('pptp-modal-defroute').checked;
  2031. const disabled = document.getElementById('pptp-modal-disabled').checked;
  2032. try {
  2033. const res = await fetch(`${API_BASE}/vpn/pptp/clients`, {
  2034. method: 'POST',
  2035. headers: { 'Content-Type': 'application/json' },
  2036. body: JSON.stringify({
  2037. name,
  2038. connect_to: server,
  2039. username: user,
  2040. password: pass,
  2041. require_mppe: mppe,
  2042. default_route: defRoute,
  2043. auto_reconnect: true,
  2044. disabled
  2045. })
  2046. });
  2047. if (res.ok) {
  2048. showToast('PPTP Saved', `Client ${name} configuration saved`, 'success');
  2049. closePPTPModal();
  2050. loadPPTP(false);
  2051. fetchData(false);
  2052. }
  2053. } catch (err) {
  2054. showToast('Error', err.message, 'error');
  2055. }
  2056. }
  2057. async function connectPPTPInstance(name) {
  2058. try {
  2059. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2060. if (res.ok) {
  2061. showToast('Connecting', `Dialing PPTP ${name}...`, 'info');
  2062. setTimeout(() => loadPPTP(false), 2000);
  2063. }
  2064. } catch (err) {
  2065. showToast('Error', err.message, 'error');
  2066. }
  2067. }
  2068. async function disconnectPPTPInstance(name) {
  2069. try {
  2070. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2071. if (res.ok) {
  2072. showToast('Disconnected', `PPTP tunnel ${name} terminated`, 'info');
  2073. loadPPTP(false);
  2074. }
  2075. } catch (err) {
  2076. showToast('Error', err.message, 'error');
  2077. }
  2078. }
  2079. async function togglePPTPState(name, enable) {
  2080. try {
  2081. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/state`, {
  2082. method: 'POST',
  2083. headers: { 'Content-Type': 'application/json' },
  2084. body: JSON.stringify({ enabled: enable })
  2085. });
  2086. if (res.ok) {
  2087. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2088. loadPPTP(false);
  2089. }
  2090. } catch (err) {
  2091. showToast('Error', err.message, 'error');
  2092. }
  2093. }
  2094. async function deletePPTPInstance(name) {
  2095. if (!confirm(`Are you sure you want to delete PPTP client ${name}?`)) return;
  2096. try {
  2097. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2098. if (res.ok) {
  2099. showToast('Deleted', `PPTP client ${name} removed`, 'success');
  2100. loadPPTP(false);
  2101. fetchData(false);
  2102. }
  2103. } catch (err) {
  2104. showToast('Error', err.message, 'error');
  2105. }
  2106. }
  2107. // ---------------- Modal & Helper Functions ----------------
  2108. function openVlanModal(defaultParent = '') {
  2109. const select = document.getElementById('vlan-parent');
  2110. select.innerHTML = '';
  2111. const allIfaces = state.interfaces || [];
  2112. const eligible = allIfaces.filter(i => supportsVLAN(i));
  2113. if (eligible.length === 0) {
  2114. const opt = document.createElement('option');
  2115. opt.value = '';
  2116. opt.innerText = 'No VLAN-capable interfaces available';
  2117. select.appendChild(opt);
  2118. } else {
  2119. eligible.forEach(i => {
  2120. const opt = document.createElement('option');
  2121. opt.value = i.name;
  2122. opt.innerText = `${i.name} (${i.role || i.type || 'Ethernet'} - ${i.state})`;
  2123. if (i.name === defaultParent) opt.selected = true;
  2124. select.appendChild(opt);
  2125. });
  2126. }
  2127. document.getElementById('vlan-id').value = '';
  2128. document.getElementById('vlan-name').value = '';
  2129. document.getElementById('vlan-ip').value = '';
  2130. document.getElementById('vlan-desc').value = '';
  2131. autoSuggestVlanName();
  2132. document.getElementById('vlan-modal').classList.remove('hidden');
  2133. }
  2134. function closeVlanModal() {
  2135. document.getElementById('vlan-modal').classList.add('hidden');
  2136. }
  2137. function autoSuggestVlanName() {
  2138. const parent = document.getElementById('vlan-parent').value;
  2139. if (!parent) return;
  2140. const id = document.getElementById('vlan-id').value;
  2141. const nameInput = document.getElementById('vlan-name');
  2142. if (parent && id) nameInput.placeholder = `${parent}.${id}`;
  2143. }
  2144. function setSubnetPreset(cidr) {
  2145. const ipInput = document.getElementById('vlan-ip');
  2146. const id = document.getElementById('vlan-id').value || '10';
  2147. ipInput.value = `192.168.${id}.1${cidr}`;
  2148. }
  2149. async function submitCreateVlan(e) {
  2150. e.preventDefault();
  2151. const btn = document.getElementById('vlan-submit-btn');
  2152. btn.disabled = true;
  2153. btn.innerText = 'Creating...';
  2154. const parent = document.getElementById('vlan-parent').value;
  2155. if (!parent) {
  2156. showToast('Error', 'Please select a valid VLAN-capable parent interface', 'error');
  2157. btn.disabled = false;
  2158. btn.innerText = 'Create VLAN';
  2159. return;
  2160. }
  2161. const id = parseInt(document.getElementById('vlan-id').value, 10);
  2162. const name = document.getElementById('vlan-name').value.trim();
  2163. const ip = document.getElementById('vlan-ip').value.trim();
  2164. const role = document.getElementById('vlan-role').value;
  2165. const desc = document.getElementById('vlan-desc').value.trim();
  2166. try {
  2167. const res = await fetch(`${API_BASE}/vlans`, {
  2168. method: 'POST',
  2169. headers: { 'Content-Type': 'application/json' },
  2170. body: JSON.stringify({
  2171. parent_name: parent,
  2172. vlan_id: id,
  2173. name: name,
  2174. ip_address: ip,
  2175. role: role,
  2176. description: desc,
  2177. mtu: 1500,
  2178. auto_up: true
  2179. })
  2180. });
  2181. const data = await res.json();
  2182. if (res.ok) {
  2183. showToast('VLAN Created', `Created ${data.name} (VLAN ${data.vlan_id})`, 'success');
  2184. state.expandedParents.add(parent);
  2185. closeVlanModal();
  2186. await fetchData(true);
  2187. if (state.activeTab !== 'interfaces') navigate('interfaces');
  2188. } else {
  2189. showToast('Creation Failed', data.message || 'Failed to create VLAN', 'error');
  2190. }
  2191. } catch (err) {
  2192. showToast('Error', err.message, 'error');
  2193. } finally {
  2194. btn.disabled = false;
  2195. btn.innerText = 'Create VLAN';
  2196. }
  2197. }
  2198. async function confirmDeleteVlan(name) {
  2199. if (!confirm(`Delete VLAN interface ${name}?`)) return;
  2200. try {
  2201. const res = await fetch(`${API_BASE}/vlans/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2202. if (res.ok) {
  2203. showToast('VLAN Deleted', `Interface ${name} removed`, 'success');
  2204. closeIfaceModal();
  2205. fetchData(true);
  2206. }
  2207. } catch (err) {
  2208. showToast('Error', err.message, 'error');
  2209. }
  2210. }
  2211. function openIfaceModal(name) {
  2212. const iface = (state.interfaces || []).find(i => i.name === name);
  2213. if (!iface) return;
  2214. state.currentModalIface = iface.name;
  2215. document.getElementById('modal-iface-name').innerText = iface.name;
  2216. document.getElementById('modal-iface-badge').innerText = iface.is_vlan ? `VLAN ${iface.vlan_id}` : iface.type;
  2217. document.getElementById('modal-iface-mtu').value = iface.mtu;
  2218. document.getElementById('modal-iface-role').value = iface.role || 'LAN';
  2219. document.getElementById('modal-iface-desc').value = iface.description || '';
  2220. const delBtn = document.getElementById('modal-delete-vlan-btn');
  2221. if (iface.is_vlan) {
  2222. delBtn.classList.remove('hidden');
  2223. } else {
  2224. delBtn.classList.add('hidden');
  2225. }
  2226. renderModalIPs(iface);
  2227. document.getElementById('iface-modal').classList.remove('hidden');
  2228. }
  2229. function renderModalIPs(iface) {
  2230. const container = document.getElementById('modal-ip-list');
  2231. container.innerHTML = '';
  2232. const addrs = [...(iface.ipv4 || []), ...(iface.ipv6 || [])];
  2233. if (addrs.length === 0) {
  2234. container.innerHTML = `<span class="text-slate-500 text-xs font-sans">No IP addresses currently bound</span>`;
  2235. return;
  2236. }
  2237. addrs.forEach(addr => {
  2238. const row = document.createElement('div');
  2239. row.className = 'flex items-center justify-between p-2 rounded bg-slate-900 border border-slate-800';
  2240. row.innerHTML = `
  2241. <span class="text-white">${addr}</span>
  2242. <button onclick="removeInterfaceIP('${addr}')" class="text-[11px] text-rose-400 hover:text-rose-300 font-sans">Remove</button>
  2243. `;
  2244. container.appendChild(row);
  2245. });
  2246. }
  2247. function closeIfaceModal() {
  2248. document.getElementById('iface-modal').classList.add('hidden');
  2249. state.currentModalIface = null;
  2250. }
  2251. async function setIfaceState(name, newState) {
  2252. await toggleInterfaceState(name, newState);
  2253. const updated = (state.interfaces || []).find(i => i.name === name);
  2254. if (updated) openIfaceModal(name);
  2255. }
  2256. async function applyMTU() {
  2257. const mtu = parseInt(document.getElementById('modal-iface-mtu').value, 10);
  2258. try {
  2259. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/mtu`, {
  2260. method: 'POST',
  2261. headers: { 'Content-Type': 'application/json' },
  2262. body: JSON.stringify({ mtu })
  2263. });
  2264. if (res.ok) {
  2265. showToast('MTU Applied', `Set MTU to ${mtu} on ${state.currentModalIface}`, 'success');
  2266. fetchData(false);
  2267. }
  2268. } catch (err) {
  2269. showToast('Error', err.message, 'error');
  2270. }
  2271. }
  2272. async function addInterfaceIP() {
  2273. const ip = document.getElementById('modal-new-ip').value.trim();
  2274. if (!ip) return;
  2275. try {
  2276. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  2277. method: 'POST',
  2278. headers: { 'Content-Type': 'application/json' },
  2279. body: JSON.stringify({ ip })
  2280. });
  2281. if (res.ok) {
  2282. showToast('IP Added', `Bound ${ip} to ${state.currentModalIface}`, 'success');
  2283. document.getElementById('modal-new-ip').value = '';
  2284. await fetchData(false);
  2285. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  2286. if (iface) renderModalIPs(iface);
  2287. } else {
  2288. const err = await res.json();
  2289. showToast('Error', err.error || err.message || 'Failed to add IP address', 'error');
  2290. }
  2291. } catch (err) {
  2292. showToast('Error', err.message, 'error');
  2293. }
  2294. }
  2295. async function removeInterfaceIP(ip) {
  2296. if (!confirm(`Remove IP ${ip}?`)) return;
  2297. try {
  2298. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  2299. method: 'DELETE',
  2300. headers: { 'Content-Type': 'application/json' },
  2301. body: JSON.stringify({ ip })
  2302. });
  2303. if (res.ok) {
  2304. showToast('IP Removed', `Removed ${ip}`, 'success');
  2305. await fetchData(false);
  2306. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  2307. if (iface) renderModalIPs(iface);
  2308. }
  2309. } catch (err) {
  2310. showToast('Error', err.message, 'error');
  2311. }
  2312. }
  2313. async function saveInterfaceMetadata() {
  2314. const role = document.getElementById('modal-iface-role').value;
  2315. const desc = document.getElementById('modal-iface-desc').value.trim();
  2316. try {
  2317. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/metadata`, {
  2318. method: 'POST',
  2319. headers: { 'Content-Type': 'application/json' },
  2320. body: JSON.stringify({ role, description: desc })
  2321. });
  2322. if (res.ok) {
  2323. showToast('Saved', 'Metadata updated', 'success');
  2324. closeIfaceModal();
  2325. fetchData(false);
  2326. }
  2327. } catch (err) {
  2328. showToast('Error', err.message, 'error');
  2329. }
  2330. }
  2331. // ======================== MIKROTIK FIREWALL (/ip firewall) ========================
  2332. state.fwSubTab = 'filter';
  2333. state.routesSubTab = 'routes';
  2334. function renderRuleFlag(disabled, hasComment) {
  2335. let flags = '';
  2336. if (disabled) flags += '<span class="text-rose-400 font-bold" title="Disabled">X</span>';
  2337. if (hasComment) flags += '<span class="text-amber-400 font-bold ml-1" title="Has Comment">C</span>';
  2338. return flags || '<span class="text-slate-600">-</span>';
  2339. }
  2340. function renderActionBadge(action) {
  2341. const act = (action || '').toLowerCase();
  2342. let color = 'bg-slate-800 text-slate-300';
  2343. if (act === 'accept') color = 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30';
  2344. else if (act === 'drop' || act === 'reject') color = 'bg-rose-500/20 text-rose-300 border border-rose-500/30';
  2345. else if (act === 'masquerade' || act === 'src-nat' || act === 'dst-nat') color = 'bg-amber-500/20 text-amber-300 border border-amber-500/30';
  2346. else if (act.startsWith('mark-')) color = 'bg-purple-500/20 text-purple-300 border border-purple-500/30';
  2347. else if (act === 'log') color = 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30';
  2348. return `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold ${color}">${action}</span>`;
  2349. }
  2350. function switchFWSubTab(tab) {
  2351. state.fwSubTab = tab;
  2352. const tabs = ['filter', 'nat', 'mangle', 'addrlist', 'geo', 'connections'];
  2353. tabs.forEach(t => {
  2354. const panel = document.getElementById(`fw-subtab-${t}`);
  2355. const btn = document.getElementById(`fw-subtab-btn-${t}`);
  2356. if (panel) {
  2357. if (t === tab) panel.classList.remove('hidden');
  2358. else panel.classList.add('hidden');
  2359. }
  2360. if (btn) {
  2361. if (t === tab) {
  2362. 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';
  2363. } else {
  2364. 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';
  2365. }
  2366. }
  2367. });
  2368. const addBtn = document.getElementById('fw-primary-add-btn');
  2369. if (addBtn) {
  2370. if (tab === 'filter') addBtn.innerHTML = '<span>+ Add Filter Rule</span>';
  2371. else if (tab === 'nat') addBtn.innerHTML = '<span>+ Add NAT Rule</span>';
  2372. else if (tab === 'mangle') addBtn.innerHTML = '<span>+ Add Mangle Rule</span>';
  2373. else if (tab === 'addrlist') addBtn.innerHTML = '<span>+ Add Address List</span>';
  2374. else if (tab === 'geo') addBtn.innerHTML = '<span>⚙️ Schedule Settings</span>';
  2375. else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
  2376. }
  2377. if (tab === 'geo') loadGeoIP();
  2378. if (tab === 'connections') loadConnections();
  2379. }
  2380. function openCurrentFWModal() {
  2381. if (state.fwSubTab === 'filter') openAddFilterModal();
  2382. else if (state.fwSubTab === 'nat') openAddNATModal();
  2383. else if (state.fwSubTab === 'mangle') openAddMangleModal();
  2384. else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
  2385. else if (state.fwSubTab === 'geo') openGeoIntervalModal();
  2386. else if (state.fwSubTab === 'connections') loadConnections();
  2387. }
  2388. async function loadFirewall(populateDropdowns = true) {
  2389. try {
  2390. const [summaryRes, filterRes, natRes, mangleRes, addrlistRes, geoStatusRes, geoCountriesRes] = await Promise.all([
  2391. fetch(`${API_BASE}/firewall/summary`),
  2392. fetch(`${API_BASE}/firewall/filter`),
  2393. fetch(`${API_BASE}/firewall/nat`),
  2394. fetch(`${API_BASE}/firewall/mangle`),
  2395. fetch(`${API_BASE}/firewall/address-lists`),
  2396. fetch(`${API_BASE}/firewall/geoip/status`),
  2397. fetch(`${API_BASE}/firewall/geoip/countries`)
  2398. ]);
  2399. if (summaryRes.ok) state.fwSummary = await summaryRes.json();
  2400. if (filterRes.ok) state.filterRules = await filterRes.json();
  2401. if (natRes.ok) state.natRules = await natRes.json();
  2402. if (mangleRes.ok) state.mangleRules = await mangleRes.json();
  2403. if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
  2404. if (geoStatusRes.ok) state.geoStatus = await geoStatusRes.json();
  2405. if (geoCountriesRes.ok) state.geoCountries = await geoCountriesRes.json();
  2406. // Badges
  2407. const bFilter = document.getElementById('fw-badge-filter');
  2408. if (bFilter) bFilter.innerText = (state.filterRules || []).length;
  2409. const bNat = document.getElementById('fw-badge-nat');
  2410. if (bNat) bNat.innerText = (state.natRules || []).length;
  2411. const bMangle = document.getElementById('fw-badge-mangle');
  2412. if (bMangle) bMangle.innerText = (state.mangleRules || []).length;
  2413. const bAddr = document.getElementById('fw-badge-addrlist');
  2414. if (bAddr) bAddr.innerText = (state.addressLists || []).length;
  2415. const bGeo = document.getElementById('fw-badge-geo');
  2416. if (bGeo) bGeo.innerText = state.geoStatus?.enabled_count || 0;
  2417. renderFilterRules();
  2418. renderNATRules();
  2419. renderMangleRules();
  2420. renderAddressLists();
  2421. renderGeoCountries();
  2422. if (state.fwSubTab === 'connections') {
  2423. loadConnections();
  2424. }
  2425. } catch (err) {
  2426. console.error('Failed to load firewall:', err);
  2427. }
  2428. }
  2429. // ----------------- Filter Rules -----------------
  2430. function renderFilterRules() {
  2431. const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
  2432. const tbody = document.getElementById('filter-table-body');
  2433. const empty = document.getElementById('filter-empty');
  2434. if (!tbody) return;
  2435. tbody.innerHTML = '';
  2436. const rules = (state.filterRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2437. document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
  2438. if (rules.length === 0) {
  2439. empty?.classList.remove('hidden');
  2440. return;
  2441. }
  2442. empty?.classList.add('hidden');
  2443. rules.forEach((r, idx) => {
  2444. const tr = document.createElement('tr');
  2445. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2446. const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
  2447. const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
  2448. let actionExtra = '';
  2449. if (r.action === 'reject') {
  2450. actionExtra = `<span class="block text-[10px] text-rose-300 font-mono mt-0.5">(${r.reject_with || 'icmp-net-unreach'})</span>`;
  2451. } else if (r.action === 'jump') {
  2452. actionExtra = `<span class="block text-[10px] text-yellow-300 font-mono mt-0.5">&rarr; ${r.jump_target || '-'}</span>`;
  2453. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  2454. actionExtra = `<span class="block text-[10px] text-emerald-300 font-mono mt-0.5">&rarr; ${r.address_list || '-'}</span>`;
  2455. } else if (r.action === 'log' && r.log_prefix) {
  2456. actionExtra = `<span class="block text-[10px] text-slate-400 font-mono mt-0.5">${r.log_prefix}</span>`;
  2457. }
  2458. tr.innerHTML = `
  2459. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  2460. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  2461. <td class="py-2.5 px-3 font-bold text-white">${r.chain}</td>
  2462. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  2463. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  2464. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}</td>
  2465. <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
  2466. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  2467. <td class="py-2.5 px-3">${renderActionBadge(r.action)}${actionExtra}</td>
  2468. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2469. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2470. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2471. </td>
  2472. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2473. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2474. <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2475. <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2476. <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>
  2477. <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2478. <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2479. </td>
  2480. `;
  2481. tbody.appendChild(tr);
  2482. });
  2483. }
  2484. function formatTarget(addr, list, geo) {
  2485. const parts = [];
  2486. if (addr) parts.push(`<span>${addr}</span>`);
  2487. if (list) {
  2488. const inv = list.startsWith('!') ? '!' : '';
  2489. const clean = list.replace(/^!/, '');
  2490. 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>`);
  2491. }
  2492. if (geo) {
  2493. const inv = geo.startsWith('!') ? '!' : '';
  2494. const clean = geo.replace(/^!/, '').replace(/^geo:/, '');
  2495. 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>`);
  2496. }
  2497. if (parts.length === 0) return '<span class="text-slate-600">0.0.0.0/0</span>';
  2498. return parts.join(' ');
  2499. }
  2500. function populateInterfaceSelect(selectId, currentVal = '') {
  2501. const sel = document.getElementById(selectId);
  2502. if (!sel) return;
  2503. sel.innerHTML = '<option value="">(Any Interface)</option>';
  2504. (state.interfaces || []).forEach(i => {
  2505. const opt = document.createElement('option');
  2506. opt.value = i.name;
  2507. opt.innerText = `${i.name} (${i.role || i.type})`;
  2508. if (i.name === currentVal) opt.selected = true;
  2509. sel.appendChild(opt);
  2510. });
  2511. }
  2512. function populateAddressListSelect(selectId, currentVal = '') {
  2513. const sel = document.getElementById(selectId);
  2514. if (!sel) return;
  2515. sel.innerHTML = '<option value="">(None)</option>';
  2516. const cleanVal = (currentVal || '').replace(/^!/, '');
  2517. const customNames = Array.from(new Set((state.addressLists || []).map(a => a.name))).sort();
  2518. customNames.forEach(name => {
  2519. const count = (state.addressLists || []).filter(a => a.name === name).length;
  2520. const opt = document.createElement('option');
  2521. opt.value = name;
  2522. opt.innerText = `${name} (${count} entries)`;
  2523. if (name === cleanVal) opt.selected = true;
  2524. sel.appendChild(opt);
  2525. });
  2526. if (cleanVal && !sel.querySelector(`option[value="${cleanVal}"]`)) {
  2527. const opt = document.createElement('option');
  2528. opt.value = cleanVal;
  2529. opt.innerText = cleanVal;
  2530. opt.selected = true;
  2531. sel.appendChild(opt);
  2532. }
  2533. populateCommonAddrListDatalist();
  2534. }
  2535. function populateCommonAddrListDatalist() {
  2536. const dl = document.getElementById('fw-addrlist-datalist');
  2537. if (!dl) return;
  2538. dl.innerHTML = '';
  2539. const names = Array.from(new Set((state.addressLists || []).map(a => a.name).filter(Boolean))).sort();
  2540. names.forEach(name => {
  2541. const opt = document.createElement('option');
  2542. opt.value = name;
  2543. dl.appendChild(opt);
  2544. });
  2545. }
  2546. function populateGeoIPSelect(selectId, currentVal = '') {
  2547. const sel = document.getElementById(selectId);
  2548. if (!sel) return;
  2549. sel.innerHTML = '<option value="">(None)</option>';
  2550. const cleanVal = (currentVal || '').replace(/^!/, '').replace(/^geo:/, '').toUpperCase();
  2551. // Presets optgroup
  2552. const grpPresets = document.createElement('optgroup');
  2553. grpPresets.label = '⚡ Regional Presets';
  2554. const presets = [
  2555. { code: 'EU', label: '🇪🇺 European Union (EU - 27 countries)' },
  2556. { code: 'BALKANS', label: '🏛️ Balkans (GR, CY, BG, RO, AL, etc.)' },
  2557. { code: 'BLOCKLIST', label: '🛡️ High-Risk Blocklist (CN, RU, IR, KP, BY)' }
  2558. ];
  2559. presets.forEach(p => {
  2560. const opt = document.createElement('option');
  2561. opt.value = p.code;
  2562. opt.innerText = p.label;
  2563. if (p.code === cleanVal) opt.selected = true;
  2564. grpPresets.appendChild(opt);
  2565. });
  2566. sel.appendChild(grpPresets);
  2567. // All Countries optgroup
  2568. const grpCountries = document.createElement('optgroup');
  2569. grpCountries.label = '🌍 All Countries';
  2570. const countries = (state.geoCountries || []).slice().sort((a, b) => a.name.localeCompare(b.name));
  2571. countries.forEach(c => {
  2572. const opt = document.createElement('option');
  2573. opt.value = c.code;
  2574. const subnetsInfo = c.subnet_count ? ` [${c.subnet_count.toLocaleString()} subnets]` : '';
  2575. opt.innerText = `${c.name} (${c.code})${subnetsInfo}`;
  2576. if (c.code === cleanVal) opt.selected = true;
  2577. grpCountries.appendChild(opt);
  2578. });
  2579. sel.appendChild(grpCountries);
  2580. }
  2581. // ==================== FIREWALL FILTER MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  2582. function switchFwRuleTab(tab) {
  2583. state.activeFwRuleTab = tab;
  2584. document.querySelectorAll('.fw-rule-tab-btn').forEach(btn => {
  2585. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  2586. btn.classList.add('text-slate-400', 'border-transparent');
  2587. });
  2588. const activeBtn = document.getElementById(`fw-tab-btn-${tab}`);
  2589. if (activeBtn) {
  2590. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  2591. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  2592. }
  2593. document.querySelectorAll('.fw-rule-pane').forEach(p => p.classList.add('hidden'));
  2594. const activePane = document.getElementById(`fw-pane-${tab}`);
  2595. if (activePane) activePane.classList.remove('hidden');
  2596. if (tab === 'statistics') {
  2597. startFwStatPolling();
  2598. } else {
  2599. stopFwStatPolling();
  2600. }
  2601. }
  2602. function toggleFwField(fieldKey, expand) {
  2603. const plusBtn = document.getElementById(`fw-plus-${fieldKey}`);
  2604. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  2605. if (!plusBtn || !fieldBox) return;
  2606. if (expand) {
  2607. plusBtn.classList.add('hidden');
  2608. fieldBox.classList.remove('hidden');
  2609. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  2610. if (valInput) valInput.focus();
  2611. } else {
  2612. fieldBox.classList.add('hidden');
  2613. plusBtn.classList.remove('hidden');
  2614. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  2615. if (valInput) {
  2616. if (valInput.tagName === 'SELECT') {
  2617. valInput.selectedIndex = 0;
  2618. } else {
  2619. valInput.value = '';
  2620. }
  2621. }
  2622. const invInput = document.getElementById(`fw-inv-${fieldKey}`);
  2623. if (invInput) invInput.checked = false;
  2624. if (fieldKey === 'cs') {
  2625. ['filter-modal-cs-established', 'filter-modal-cs-related', 'filter-modal-cs-new', 'filter-modal-cs-invalid', 'filter-modal-cs-untracked'].forEach(id => {
  2626. const el = document.getElementById(id);
  2627. if (el) el.checked = false;
  2628. });
  2629. }
  2630. if (fieldKey === 'natstate') {
  2631. ['filter-modal-nat-srcnat', 'filter-modal-nat-dstnat'].forEach(id => {
  2632. const el = document.getElementById(id);
  2633. if (el) el.checked = false;
  2634. });
  2635. }
  2636. if (fieldKey === 'days') {
  2637. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  2638. const el = document.getElementById(`fw-day-${d}`);
  2639. if (el) el.checked = true;
  2640. });
  2641. }
  2642. }
  2643. }
  2644. function setFwFieldVal(fieldKey, value, hasInvert = false) {
  2645. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  2646. toggleFwField(fieldKey, true);
  2647. let strVal = String(value);
  2648. if (hasInvert) {
  2649. const inv = strVal.startsWith('!');
  2650. if (inv) strVal = strVal.slice(1);
  2651. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  2652. if (invEl) invEl.checked = inv;
  2653. }
  2654. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  2655. if (valEl) valEl.value = strVal;
  2656. } else {
  2657. toggleFwField(fieldKey, false);
  2658. }
  2659. }
  2660. function getFwFieldVal(fieldKey, hasInvert = false) {
  2661. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  2662. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  2663. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  2664. let v = valEl ? valEl.value.trim() : '';
  2665. if (!v) return '';
  2666. if (hasInvert) {
  2667. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  2668. if (invEl && invEl.checked) {
  2669. v = '!' + v.replace(/^!/, '');
  2670. }
  2671. }
  2672. return v;
  2673. }
  2674. function toggleMaximizeFilterModal() {
  2675. const win = document.getElementById('filter-modal-window');
  2676. if (!win) return;
  2677. if (win.classList.contains('max-w-[720px]')) {
  2678. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  2679. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  2680. } else {
  2681. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  2682. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  2683. }
  2684. }
  2685. function openAddFilterModal() {
  2686. switchFwRuleTab('general');
  2687. const badge = document.getElementById('fw-modal-badge');
  2688. if (badge) badge.innerText = 'New...';
  2689. document.getElementById('filter-modal-id').value = '';
  2690. document.getElementById('filter-modal-enabled').checked = true;
  2691. document.getElementById('filter-modal-comment').value = '';
  2692. document.getElementById('filter-modal-chain').value = 'forward';
  2693. document.getElementById('filter-modal-action').value = 'accept';
  2694. document.getElementById('filter-modal-log').checked = false;
  2695. populateInterfaceSelect('fw-val-iniface');
  2696. populateInterfaceSelect('fw-val-outiface');
  2697. populateAddressListSelect('fw-val-srclist');
  2698. populateAddressListSelect('fw-val-dstlist');
  2699. populateGeoIPSelect('fw-val-srcgeo');
  2700. populateGeoIPSelect('fw-val-dstgeo');
  2701. const allFieldKeys = [
  2702. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  2703. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  2704. 'routingmark', 'conntype', 'cs', 'natstate',
  2705. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  2706. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  2707. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  2708. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  2709. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  2710. ];
  2711. allFieldKeys.forEach(k => toggleFwField(k, false));
  2712. resetCurrentRuleCounters();
  2713. toggleFilterActionFields();
  2714. document.getElementById('filter-modal').classList.remove('hidden');
  2715. }
  2716. function openEditFilterModal(id) {
  2717. const r = (state.filterRules || []).find(rule => rule.id === id);
  2718. if (!r) return;
  2719. switchFwRuleTab('general');
  2720. const badge = document.getElementById('fw-modal-badge');
  2721. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  2722. document.getElementById('filter-modal-id').value = r.id;
  2723. document.getElementById('filter-modal-enabled').checked = !r.disabled;
  2724. document.getElementById('filter-modal-comment').value = r.comment || '';
  2725. document.getElementById('filter-modal-chain').value = r.chain || 'forward';
  2726. document.getElementById('filter-modal-action').value = r.action || 'accept';
  2727. document.getElementById('filter-modal-log').checked = !!r.log;
  2728. populateInterfaceSelect('fw-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  2729. populateInterfaceSelect('fw-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  2730. populateAddressListSelect('fw-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  2731. populateAddressListSelect('fw-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  2732. populateGeoIPSelect('fw-val-srcgeo', r.src_geoip || '');
  2733. populateGeoIPSelect('fw-val-dstgeo', r.dst_geoip || '');
  2734. setFwFieldVal('src', r.src_address, true);
  2735. setFwFieldVal('dst', r.dst_address, true);
  2736. setFwFieldVal('srclist', r.src_address_list, true);
  2737. setFwFieldVal('dstlist', r.dst_address_list, true);
  2738. setFwFieldVal('srcgeo', r.src_geoip, true);
  2739. setFwFieldVal('dstgeo', r.dst_geoip, true);
  2740. if (r.protocol && r.protocol !== 'all') {
  2741. setFwFieldVal('proto', r.protocol, true);
  2742. } else {
  2743. toggleFwField('proto', false);
  2744. }
  2745. setFwFieldVal('sport', r.src_port, true);
  2746. setFwFieldVal('dport', r.dst_port, true);
  2747. setFwFieldVal('anyport', r.any_port, true);
  2748. setFwFieldVal('iniface', r.in_interface, true);
  2749. setFwFieldVal('outiface', r.out_interface, true);
  2750. setFwFieldVal('inifacelist', r.in_interface_list, true);
  2751. setFwFieldVal('outifacelist', r.out_interface_list, true);
  2752. setFwFieldVal('pktmark', r.packet_mark, true);
  2753. setFwFieldVal('connmark', r.connection_mark, true);
  2754. setFwFieldVal('routingmark', r.routing_mark, true);
  2755. setFwFieldVal('conntype', r.connection_type, false);
  2756. const states = r.connection_state || [];
  2757. if (states.length > 0) {
  2758. toggleFwField('cs', true);
  2759. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  2760. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  2761. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  2762. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  2763. document.getElementById('filter-modal-cs-untracked').checked = states.includes('untracked');
  2764. } else {
  2765. toggleFwField('cs', false);
  2766. }
  2767. const natStates = r.connection_nat_state || [];
  2768. if (natStates.length > 0) {
  2769. toggleFwField('natstate', true);
  2770. document.getElementById('filter-modal-nat-srcnat').checked = natStates.includes('srcnat');
  2771. document.getElementById('filter-modal-nat-dstnat').checked = natStates.includes('dstnat');
  2772. } else {
  2773. toggleFwField('natstate', false);
  2774. }
  2775. // Advanced tab fields
  2776. setFwFieldVal('layer7', r.layer7_protocol, false);
  2777. setFwFieldVal('content', r.content, false);
  2778. setFwFieldVal('connbytes', r.connection_bytes, false);
  2779. setFwFieldVal('connrate', r.connection_rate, false);
  2780. setFwFieldVal('pcc', r.pcc, false);
  2781. setFwFieldVal('srcmac', r.src_mac_address, true);
  2782. setFwFieldVal('outbridgeport', r.out_bridge_port, false);
  2783. setFwFieldVal('inbridgeport', r.in_bridge_port, false);
  2784. setFwFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  2785. setFwFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  2786. setFwFieldVal('ipsec', r.ipsec_policy, false);
  2787. setFwFieldVal('tlshost', r.tls_host, false);
  2788. setFwFieldVal('ingresspriority', r.ingress_priority, false);
  2789. setFwFieldVal('priority', r.priority, false);
  2790. setFwFieldVal('dscp', r.dscp, false);
  2791. setFwFieldVal('tcpmss', r.tcp_mss, false);
  2792. if (r.tos) {
  2793. const tosEl = document.getElementById('fw-val-tos');
  2794. if (tosEl) tosEl.value = r.tos;
  2795. }
  2796. setFwFieldVal('pktsize', r.packet_size, false);
  2797. setFwFieldVal('random', r.random, false);
  2798. setFwFieldVal('tcpflags', r.tcp_flags, false);
  2799. setFwFieldVal('icmpoptions', r.icmp_options, false);
  2800. setFwFieldVal('ipv4options', r.ipv4_options, false);
  2801. setFwFieldVal('ttl', r.ttl, false);
  2802. // Extra tab fields
  2803. setFwFieldVal('time', r.time, false);
  2804. if (r.days) {
  2805. toggleFwField('days', true);
  2806. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  2807. const chk = document.getElementById(`fw-day-${d}`);
  2808. if (chk) chk.checked = r.days.includes(d);
  2809. });
  2810. } else {
  2811. toggleFwField('days', false);
  2812. }
  2813. setFwFieldVal('limit', r.limit, false);
  2814. setFwFieldVal('dstlimit', r.dst_limit, false);
  2815. setFwFieldVal('psd', r.psd, false);
  2816. // Action fields
  2817. if (r.reject_with) {
  2818. const rwEl = document.getElementById('filter-modal-rejectwith');
  2819. if (rwEl) rwEl.value = r.reject_with;
  2820. }
  2821. if (r.jump_target) {
  2822. const jtEl = document.getElementById('filter-modal-jumptarget');
  2823. if (jtEl) jtEl.value = r.jump_target;
  2824. }
  2825. if (r.address_list) {
  2826. const alEl = document.getElementById('filter-modal-action-addrlist');
  2827. if (alEl) alEl.value = r.address_list;
  2828. }
  2829. if (r.address_list_timeout) {
  2830. const toEl = document.getElementById('filter-modal-action-timeout');
  2831. if (toEl) toEl.value = r.address_list_timeout;
  2832. }
  2833. setFwFieldVal('logprefix', r.log_prefix, false);
  2834. // Statistics
  2835. const bEl = document.getElementById('fw-stat-bytes');
  2836. const pEl = document.getElementById('fw-stat-packets');
  2837. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  2838. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  2839. state.fwLastBytes = r.bytes || 0;
  2840. state.fwLastPackets = r.packets || 0;
  2841. state.fwLastTimestamp = Date.now();
  2842. state.fwStatRateHistory = new Array(30).fill(0);
  2843. state.fwStatPktHistory = new Array(30).fill(0);
  2844. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  2845. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  2846. toggleFilterActionFields();
  2847. document.getElementById('filter-modal').classList.remove('hidden');
  2848. }
  2849. function closeFilterModal() {
  2850. stopFwStatPolling();
  2851. document.getElementById('filter-modal').classList.add('hidden');
  2852. }
  2853. function toggleFilterActionFields() {
  2854. const act = document.getElementById('filter-modal-action')?.value || 'accept';
  2855. const rejectBox = document.getElementById('filter-action-reject-box');
  2856. const jumpBox = document.getElementById('filter-action-jump-box');
  2857. const addrBox = document.getElementById('filter-action-addrlist-box');
  2858. if (rejectBox) {
  2859. if (act === 'reject') rejectBox.classList.remove('hidden');
  2860. else rejectBox.classList.add('hidden');
  2861. }
  2862. if (jumpBox) {
  2863. if (act === 'jump') jumpBox.classList.remove('hidden');
  2864. else jumpBox.classList.add('hidden');
  2865. }
  2866. if (addrBox) {
  2867. if (act === 'add-dst-to-address-list' || act === 'add-src-to-address-list' || act.includes('address-list') || act.includes('address list')) {
  2868. addrBox.classList.remove('hidden');
  2869. } else {
  2870. addrBox.classList.add('hidden');
  2871. }
  2872. }
  2873. if (act === 'log') {
  2874. const logEl = document.getElementById('filter-modal-log');
  2875. if (logEl) logEl.checked = true;
  2876. toggleFwField('logprefix', true);
  2877. }
  2878. }
  2879. function toggleFwLogPrefix() {
  2880. const isLog = document.getElementById('filter-modal-log')?.checked;
  2881. toggleFwField('logprefix', !!isLog);
  2882. }
  2883. function copyFilterRule() {
  2884. document.getElementById('filter-modal-id').value = '';
  2885. const badge = document.getElementById('fw-modal-badge');
  2886. if (badge) badge.innerText = 'New...';
  2887. showToast('Rule Cloned', 'Ready to save as a new rule copy', 'info');
  2888. }
  2889. function resetCurrentRuleCounters() {
  2890. state.fwStatRateHistory = new Array(30).fill(0);
  2891. state.fwStatPktHistory = new Array(30).fill(0);
  2892. state.fwLastBytes = 0;
  2893. state.fwLastPackets = 0;
  2894. state.fwLastTimestamp = Date.now();
  2895. const bEl = document.getElementById('fw-stat-bytes');
  2896. const pEl = document.getElementById('fw-stat-packets');
  2897. const rEl = document.getElementById('fw-stat-rate');
  2898. const prEl = document.getElementById('fw-stat-pktrate');
  2899. if (bEl) bEl.value = '0 B';
  2900. if (pEl) pEl.value = '0';
  2901. if (rEl) rEl.value = '0 bps';
  2902. if (prEl) prEl.value = '0 p/s';
  2903. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  2904. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  2905. showToast('Counters Reset', 'Rule counter display reset to 0', 'info');
  2906. }
  2907. async function resetAllFwCounters() {
  2908. try {
  2909. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  2910. if (res.ok) {
  2911. resetCurrentRuleCounters();
  2912. showToast('All Counters Reset', 'All firewall counters zeroed', 'success');
  2913. loadFirewall(false);
  2914. }
  2915. } catch (err) {
  2916. showToast('Error', err.message, 'error');
  2917. }
  2918. }
  2919. async function applyFilterRule(closeAfter = false) {
  2920. const id = document.getElementById('filter-modal-id').value;
  2921. const chain = document.getElementById('filter-modal-chain').value;
  2922. const action = document.getElementById('filter-modal-action').value;
  2923. const comment = document.getElementById('filter-modal-comment').value.trim();
  2924. const enabled = document.getElementById('filter-modal-enabled').checked;
  2925. const src = getFwFieldVal('src', true);
  2926. const dst = getFwFieldVal('dst', true);
  2927. const srclist = getFwFieldVal('srclist', true);
  2928. const dstlist = getFwFieldVal('dstlist', true);
  2929. const srcgeo = getFwFieldVal('srcgeo', true);
  2930. const dstgeo = getFwFieldVal('dstgeo', true);
  2931. const proto = getFwFieldVal('proto', true);
  2932. const sport = getFwFieldVal('sport', true);
  2933. const dport = getFwFieldVal('dport', true);
  2934. const anyport = getFwFieldVal('anyport', true);
  2935. const iniface = getFwFieldVal('iniface', true);
  2936. const outiface = getFwFieldVal('outiface', true);
  2937. const inifacelist = getFwFieldVal('inifacelist', true);
  2938. const outifacelist = getFwFieldVal('outifacelist', true);
  2939. const pktmark = getFwFieldVal('pktmark', true);
  2940. const connmark = getFwFieldVal('connmark', true);
  2941. const routingmark = getFwFieldVal('routingmark', true);
  2942. const conntype = getFwFieldVal('conntype', false);
  2943. const states = [];
  2944. const csBox = document.getElementById('fw-field-cs');
  2945. if (csBox && !csBox.classList.contains('hidden')) {
  2946. if (document.getElementById('filter-modal-cs-established')?.checked) states.push('established');
  2947. if (document.getElementById('filter-modal-cs-related')?.checked) states.push('related');
  2948. if (document.getElementById('filter-modal-cs-new')?.checked) states.push('new');
  2949. if (document.getElementById('filter-modal-cs-invalid')?.checked) states.push('invalid');
  2950. if (document.getElementById('filter-modal-cs-untracked')?.checked) states.push('untracked');
  2951. }
  2952. const natStates = [];
  2953. const natBox = document.getElementById('fw-field-natstate');
  2954. if (natBox && !natBox.classList.contains('hidden')) {
  2955. if (document.getElementById('filter-modal-nat-srcnat')?.checked) natStates.push('srcnat');
  2956. if (document.getElementById('filter-modal-nat-dstnat')?.checked) natStates.push('dstnat');
  2957. }
  2958. const payload = {
  2959. id,
  2960. chain,
  2961. action,
  2962. protocol: proto || 'all',
  2963. src_address: src,
  2964. dst_address: dst,
  2965. src_port: sport,
  2966. dst_port: dport,
  2967. any_port: anyport,
  2968. in_interface: iniface,
  2969. out_interface: outiface,
  2970. in_interface_list: inifacelist,
  2971. out_interface_list: outifacelist,
  2972. packet_mark: pktmark,
  2973. connection_mark: connmark,
  2974. routing_mark: routingmark,
  2975. connection_type: conntype,
  2976. connection_state: states,
  2977. connection_nat_state: natStates,
  2978. src_address_list: srclist,
  2979. dst_address_list: dstlist,
  2980. src_geoip: srcgeo,
  2981. dst_geoip: dstgeo,
  2982. comment,
  2983. disabled: !enabled,
  2984. // Advanced tab
  2985. layer7_protocol: getFwFieldVal('layer7', false),
  2986. content: getFwFieldVal('content', false),
  2987. connection_bytes: getFwFieldVal('connbytes', false),
  2988. connection_rate: getFwFieldVal('connrate', false),
  2989. pcc: getFwFieldVal('pcc', false),
  2990. src_mac_address: getFwFieldVal('srcmac', true),
  2991. out_bridge_port: getFwFieldVal('outbridgeport', false),
  2992. in_bridge_port: getFwFieldVal('inbridgeport', false),
  2993. in_bridge_port_list: getFwFieldVal('inbridgeportlist', false),
  2994. out_bridge_port_list: getFwFieldVal('outbridgeportlist', false),
  2995. ipsec_policy: getFwFieldVal('ipsec', false),
  2996. tls_host: getFwFieldVal('tlshost', false),
  2997. ingress_priority: getFwFieldVal('ingresspriority', false),
  2998. priority: getFwFieldVal('priority', false),
  2999. dscp: getFwFieldVal('dscp', false),
  3000. tcp_mss: getFwFieldVal('tcpmss', false),
  3001. tos: document.getElementById('fw-val-tos')?.value || '',
  3002. packet_size: getFwFieldVal('pktsize', false),
  3003. random: getFwFieldVal('random', false),
  3004. tcp_flags: getFwFieldVal('tcpflags', false),
  3005. icmp_options: getFwFieldVal('icmpoptions', false),
  3006. ipv4_options: getFwFieldVal('ipv4options', false),
  3007. ttl: getFwFieldVal('ttl', false),
  3008. // Extra tab
  3009. time: getFwFieldVal('time', false),
  3010. limit: getFwFieldVal('limit', false),
  3011. dst_limit: getFwFieldVal('dstlimit', false),
  3012. psd: getFwFieldVal('psd', false),
  3013. // Action tab
  3014. reject_with: action === 'reject' ? (document.getElementById('filter-modal-rejectwith')?.value || '') : '',
  3015. jump_target: action === 'jump' ? (document.getElementById('filter-modal-jumptarget')?.value || '') : '',
  3016. address_list: action.startsWith('add-') ? (document.getElementById('filter-modal-action-addrlist')?.value || '') : '',
  3017. address_list_timeout: action.startsWith('add-') ? (document.getElementById('filter-modal-action-timeout')?.value || '') : '',
  3018. log: document.getElementById('filter-modal-log')?.checked || false,
  3019. log_prefix: getFwFieldVal('logprefix', false)
  3020. };
  3021. try {
  3022. const res = await fetch(`${API_BASE}/firewall/filter`, {
  3023. method: 'POST',
  3024. headers: { 'Content-Type': 'application/json' },
  3025. body: JSON.stringify(payload)
  3026. });
  3027. if (res.ok) {
  3028. const data = await res.json();
  3029. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  3030. loadFirewall(false);
  3031. if (closeAfter) {
  3032. closeFilterModal();
  3033. } else {
  3034. if (data.id) {
  3035. document.getElementById('filter-modal-id').value = data.id;
  3036. const badge = document.getElementById('fw-modal-badge');
  3037. if (badge) badge.innerText = `#${data.id}`;
  3038. }
  3039. }
  3040. } else {
  3041. const err = await res.json();
  3042. showToast('Error', err.message || 'Failed to save rule', 'error');
  3043. }
  3044. } catch (err) {
  3045. showToast('Error', err.message, 'error');
  3046. }
  3047. }
  3048. function submitSaveFilterRule(e) {
  3049. if (e && e.preventDefault) e.preventDefault();
  3050. return applyFilterRule(true);
  3051. }
  3052. function startFwStatPolling() {
  3053. stopFwStatPolling();
  3054. pollRuleStats();
  3055. state.fwStatInterval = setInterval(pollRuleStats, 1000);
  3056. }
  3057. function stopFwStatPolling() {
  3058. if (state.fwStatInterval) {
  3059. clearInterval(state.fwStatInterval);
  3060. state.fwStatInterval = null;
  3061. }
  3062. }
  3063. async function pollRuleStats() {
  3064. const id = document.getElementById('filter-modal-id')?.value;
  3065. if (!id) {
  3066. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory || new Array(30).fill(0), 'bps', 'fw-stat-legend-rate');
  3067. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory || new Array(30).fill(0), 'p/s', 'fw-stat-legend-pktrate');
  3068. return;
  3069. }
  3070. try {
  3071. const res = await fetch(`${API_BASE}/firewall/filter`);
  3072. if (!res.ok) return;
  3073. const rules = await res.json();
  3074. const r = rules.find(x => x.id === id);
  3075. if (!r) return;
  3076. const now = Date.now();
  3077. const dt = Math.max(0.2, (now - (state.fwLastTimestamp || now)) / 1000);
  3078. state.fwLastTimestamp = now;
  3079. const curBytes = r.bytes || 0;
  3080. const curPackets = r.packets || 0;
  3081. const deltaBytes = Math.max(0, curBytes - (state.fwLastBytes || curBytes));
  3082. const deltaPkts = Math.max(0, curPackets - (state.fwLastPackets || curPackets));
  3083. state.fwLastBytes = curBytes;
  3084. state.fwLastPackets = curPackets;
  3085. const rateBps = Math.round((deltaBytes * 8) / dt);
  3086. const ratePkt = Math.round(deltaPkts / dt);
  3087. if (!state.fwStatRateHistory) state.fwStatRateHistory = new Array(30).fill(0);
  3088. if (!state.fwStatPktHistory) state.fwStatPktHistory = new Array(30).fill(0);
  3089. state.fwStatRateHistory.push(rateBps);
  3090. if (state.fwStatRateHistory.length > 30) state.fwStatRateHistory.shift();
  3091. state.fwStatPktHistory.push(ratePkt);
  3092. if (state.fwStatPktHistory.length > 30) state.fwStatPktHistory.shift();
  3093. const bEl = document.getElementById('fw-stat-bytes');
  3094. const pEl = document.getElementById('fw-stat-packets');
  3095. const rEl = document.getElementById('fw-stat-rate');
  3096. const prEl = document.getElementById('fw-stat-pktrate');
  3097. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  3098. if (pEl) pEl.value = curPackets.toLocaleString();
  3099. if (rEl) rEl.value = formatBps(rateBps);
  3100. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  3101. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3102. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3103. } catch (e) {
  3104. console.error('Error polling rule stats', e);
  3105. }
  3106. }
  3107. function formatBps(bps) {
  3108. if (bps >= 1000000000) return (bps / 1000000000).toFixed(1) + ' Gbps';
  3109. if (bps >= 1000000) return (bps / 1000000).toFixed(1) + ' Mbps';
  3110. if (bps >= 1000) return (bps / 1000).toFixed(1) + ' kbps';
  3111. return bps + ' bps';
  3112. }
  3113. function renderFwSparkline(svgId, dataArray, unit, legendId) {
  3114. const svg = document.getElementById(svgId);
  3115. if (!svg) return;
  3116. const w = 500;
  3117. const h = 100;
  3118. const paddingRight = 45;
  3119. const graphWidth = w - paddingRight;
  3120. const maxVal = Math.max(5, ...dataArray);
  3121. const currentVal = dataArray[dataArray.length - 1] || 0;
  3122. const leg = document.getElementById(legendId);
  3123. if (leg) {
  3124. leg.innerText = unit === 'bps' ? formatBps(currentVal) : `${currentVal.toLocaleString()} p/s`;
  3125. }
  3126. let gridLines = '';
  3127. for (let i = 0; i <= 5; i++) {
  3128. const y = 8 + (i * (h - 18) / 5);
  3129. const valAtLevel = Math.round(maxVal * (5 - i) / 5);
  3130. const label = unit === 'bps' ? formatBps(valAtLevel) : `${valAtLevel} p/s`;
  3131. gridLines += `
  3132. <line x1="0" y1="${y.toFixed(1)}" x2="${graphWidth}" y2="${y.toFixed(1)}" stroke="#1e2c3e" stroke-width="1" />
  3133. <text x="${w - 2}" y="${(y + 3).toFixed(1)}" fill="#64748b" font-size="9" font-family="monospace" text-anchor="end">${label}</text>
  3134. `;
  3135. }
  3136. const step = graphWidth / (dataArray.length - 1);
  3137. const points = dataArray.map((val, idx) => {
  3138. const x = idx * step;
  3139. const y = (h - 10) - (val / maxVal) * (h - 20);
  3140. return `${x.toFixed(1)},${y.toFixed(1)}`;
  3141. });
  3142. const polylineStr = points.join(' ');
  3143. const areaPath = `M 0,${h - 10} L ${polylineStr} L ${graphWidth},${h - 10} Z`;
  3144. svg.innerHTML = `
  3145. ${gridLines}
  3146. <path d="${areaPath}" fill="rgba(14, 165, 233, 0.12)" />
  3147. <polyline fill="none" stroke="#38bdf8" stroke-width="1.8" stroke-linejoin="round" points="${polylineStr}" />
  3148. <circle cx="${graphWidth}" cy="${points[points.length - 1].split(',')[1]}" r="3" fill="#38bdf8" />
  3149. `;
  3150. }
  3151. async function moveFilterRule(id, dir) {
  3152. try {
  3153. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  3154. method: 'POST',
  3155. headers: { 'Content-Type': 'application/json' },
  3156. body: JSON.stringify({ direction: dir })
  3157. });
  3158. if (res.ok) loadFirewall(false);
  3159. } catch (err) {
  3160. showToast('Error', err.message, 'error');
  3161. }
  3162. }
  3163. async function toggleFilterRuleState(id, disabled) {
  3164. try {
  3165. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  3166. method: 'POST',
  3167. headers: { 'Content-Type': 'application/json' },
  3168. body: JSON.stringify({ disabled })
  3169. });
  3170. if (res.ok) loadFirewall(false);
  3171. } catch (err) {
  3172. showToast('Error', err.message, 'error');
  3173. }
  3174. }
  3175. async function deleteFilterRule(id) {
  3176. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  3177. try {
  3178. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3179. if (res.ok) {
  3180. showToast('Deleted', 'Filter rule removed', 'success');
  3181. loadFirewall(false);
  3182. }
  3183. } catch (err) {
  3184. showToast('Error', err.message, 'error');
  3185. }
  3186. }
  3187. // ----------------- NAT Rules -----------------
  3188. function renderNATRules() {
  3189. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  3190. const tbody = document.getElementById('nat-table-body');
  3191. const empty = document.getElementById('nat-empty');
  3192. if (!tbody) return;
  3193. tbody.innerHTML = '';
  3194. const rules = (state.natRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  3195. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  3196. if (rules.length === 0) {
  3197. empty?.classList.remove('hidden');
  3198. return;
  3199. }
  3200. empty?.classList.add('hidden');
  3201. rules.forEach((r, idx) => {
  3202. const tr = document.createElement('tr');
  3203. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  3204. let toTarget = '-';
  3205. if (r.action === 'jump') {
  3206. toTarget = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  3207. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  3208. toTarget = `<span class="text-emerald-300 font-mono font-bold">&rarr; ${r.address_list || '-'}</span>`;
  3209. } else if (r.action === 'redirect') {
  3210. toTarget = `<span class="text-amber-300 font-mono font-bold">ports:${r.to_ports || 'all'}</span>`;
  3211. } else if (r.action === 'masquerade') {
  3212. 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>`;
  3213. } else if (r.action === 'log') {
  3214. toTarget = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  3215. } else {
  3216. const parts = [r.to_addresses, r.to_ports].filter(Boolean);
  3217. toTarget = parts.length ? `<span class="text-amber-300 font-mono font-bold">${parts.join(':')}</span>` : '-';
  3218. }
  3219. const ifaces = [r.out_interface ? 'out:' + r.out_interface : '', r.in_interface ? 'in:' + r.in_interface : ''].filter(Boolean).join(' ');
  3220. tr.innerHTML = `
  3221. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  3222. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  3223. <td class="py-2.5 px-3 font-bold text-amber-400">${r.chain}</td>
  3224. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  3225. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  3226. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}${r.dst_port ? ':' + r.dst_port : ''}</td>
  3227. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  3228. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  3229. <td class="py-2.5 px-3 font-mono text-xs">${toTarget}</td>
  3230. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  3231. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  3232. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  3233. </td>
  3234. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  3235. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3236. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  3237. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  3238. <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>
  3239. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3240. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3241. </td>
  3242. `;
  3243. tbody.appendChild(tr);
  3244. });
  3245. }
  3246. // ==================== FIREWALL NAT MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  3247. function switchNATRuleTab(tab) {
  3248. state.activeNATRuleTab = tab;
  3249. document.querySelectorAll('.nat-rule-tab-btn').forEach(btn => {
  3250. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  3251. btn.classList.add('text-slate-400', 'border-transparent');
  3252. });
  3253. const activeBtn = document.getElementById(`nat-tab-btn-${tab}`);
  3254. if (activeBtn) {
  3255. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  3256. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  3257. }
  3258. document.querySelectorAll('.nat-rule-pane').forEach(p => p.classList.add('hidden'));
  3259. const activePane = document.getElementById(`nat-pane-${tab}`);
  3260. if (activePane) activePane.classList.remove('hidden');
  3261. if (tab === 'statistics') {
  3262. startNATStatPolling();
  3263. } else {
  3264. stopNATStatPolling();
  3265. }
  3266. }
  3267. function toggleNATField(fieldKey, expand) {
  3268. const plusBtn = document.getElementById(`nat-plus-${fieldKey}`);
  3269. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  3270. if (!plusBtn || !fieldBox) return;
  3271. if (expand) {
  3272. plusBtn.classList.add('hidden');
  3273. fieldBox.classList.remove('hidden');
  3274. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  3275. if (valInput) valInput.focus();
  3276. } else {
  3277. fieldBox.classList.add('hidden');
  3278. plusBtn.classList.remove('hidden');
  3279. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  3280. if (valInput) {
  3281. if (valInput.tagName === 'SELECT') {
  3282. valInput.selectedIndex = 0;
  3283. } else {
  3284. valInput.value = '';
  3285. }
  3286. }
  3287. const invInput = document.getElementById(`nat-inv-${fieldKey}`);
  3288. if (invInput) invInput.checked = false;
  3289. if (fieldKey === 'days') {
  3290. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3291. const el = document.getElementById(`nat-day-${d}`);
  3292. if (el) el.checked = true;
  3293. });
  3294. }
  3295. }
  3296. }
  3297. function setNATFieldVal(fieldKey, value, hasInvert = false) {
  3298. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  3299. toggleNATField(fieldKey, true);
  3300. let strVal = String(value);
  3301. if (hasInvert) {
  3302. const inv = strVal.startsWith('!');
  3303. if (inv) strVal = strVal.slice(1);
  3304. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  3305. if (invEl) invEl.checked = inv;
  3306. }
  3307. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  3308. if (valEl) valEl.value = strVal;
  3309. } else {
  3310. toggleNATField(fieldKey, false);
  3311. }
  3312. }
  3313. function getNATFieldVal(fieldKey, hasInvert = false) {
  3314. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  3315. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3316. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  3317. let v = valEl ? valEl.value.trim() : '';
  3318. if (!v) return '';
  3319. if (hasInvert) {
  3320. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  3321. if (invEl && invEl.checked) {
  3322. v = '!' + v.replace(/^!/, '');
  3323. }
  3324. }
  3325. return v;
  3326. }
  3327. function toggleMaximizeNATModal() {
  3328. const win = document.getElementById('nat-modal-window');
  3329. if (!win) return;
  3330. if (win.classList.contains('max-w-[720px]')) {
  3331. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3332. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3333. } else {
  3334. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3335. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3336. }
  3337. }
  3338. function handleNATChainChange() {
  3339. const ch = document.getElementById('nat-modal-chain')?.value || 'srcnat';
  3340. const actSel = document.getElementById('nat-modal-action');
  3341. if (actSel) {
  3342. if (ch === 'srcnat' && (actSel.value === 'dst-nat' || actSel.value === 'redirect')) {
  3343. actSel.value = 'masquerade';
  3344. } else if (ch === 'dstnat' && (actSel.value === 'masquerade' || actSel.value === 'src-nat')) {
  3345. actSel.value = 'dst-nat';
  3346. }
  3347. }
  3348. toggleNATActionFields();
  3349. }
  3350. function toggleNATActionFields() {
  3351. const act = document.getElementById('nat-modal-action')?.value || 'masquerade';
  3352. const rowAddr = document.getElementById('nat-row-toaddr');
  3353. const rowPort = document.getElementById('nat-row-toport');
  3354. const jumpBox = document.getElementById('nat-action-jump-box');
  3355. const addrBox = document.getElementById('nat-action-addrlist-box');
  3356. // Hide all dynamic rows first
  3357. if (rowAddr) rowAddr.classList.add('hidden');
  3358. if (rowPort) rowPort.classList.add('hidden');
  3359. if (jumpBox) jumpBox.classList.add('hidden');
  3360. if (addrBox) addrBox.classList.add('hidden');
  3361. if (['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(act)) {
  3362. if (rowAddr) rowAddr.classList.remove('hidden');
  3363. if (rowPort) rowPort.classList.remove('hidden');
  3364. } else if (act === 'redirect' || act === 'masquerade') {
  3365. if (rowPort) rowPort.classList.remove('hidden');
  3366. } else if (act === 'jump') {
  3367. if (jumpBox) jumpBox.classList.remove('hidden');
  3368. } else if (act.includes('address-list') || act.includes('address list')) {
  3369. if (addrBox) addrBox.classList.remove('hidden');
  3370. }
  3371. if (act === 'log') {
  3372. const logEl = document.getElementById('nat-modal-log');
  3373. if (logEl) logEl.checked = true;
  3374. toggleNATField('logprefix', true);
  3375. }
  3376. }
  3377. function toggleNATLogPrefix() {
  3378. const isLog = document.getElementById('nat-modal-log')?.checked;
  3379. toggleNATField('logprefix', !!isLog);
  3380. }
  3381. function openAddNATModal() {
  3382. switchNATRuleTab('general');
  3383. const badge = document.getElementById('nat-modal-badge');
  3384. if (badge) badge.innerText = 'New...';
  3385. document.getElementById('nat-modal-id').value = '';
  3386. document.getElementById('nat-modal-enabled').checked = true;
  3387. document.getElementById('nat-modal-comment').value = '';
  3388. document.getElementById('nat-modal-chain').value = 'srcnat';
  3389. document.getElementById('nat-modal-action').value = 'masquerade';
  3390. document.getElementById('nat-modal-toaddr').value = '';
  3391. document.getElementById('nat-modal-toport').value = '';
  3392. document.getElementById('nat-modal-log').checked = false;
  3393. populateInterfaceSelect('nat-val-iniface');
  3394. populateInterfaceSelect('nat-val-outiface');
  3395. populateAddressListSelect('nat-val-srclist');
  3396. populateAddressListSelect('nat-val-dstlist');
  3397. populateGeoIPSelect('nat-val-srcgeo');
  3398. populateGeoIPSelect('nat-val-dstgeo');
  3399. const allFieldKeys = [
  3400. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  3401. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  3402. 'routingmark', 'conntype',
  3403. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  3404. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  3405. 'ipsec', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  3406. 'pktsize', 'random', 'icmpoptions', 'ipv4options', 'ttl',
  3407. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  3408. ];
  3409. allFieldKeys.forEach(k => toggleNATField(k, false));
  3410. resetCurrentNATRuleCounters();
  3411. toggleNATActionFields();
  3412. document.getElementById('nat-modal').classList.remove('hidden');
  3413. }
  3414. function openEditNATModal(id) {
  3415. const r = (state.natRules || []).find(rule => rule.id === id);
  3416. if (!r) return;
  3417. switchNATRuleTab('general');
  3418. const badge = document.getElementById('nat-modal-badge');
  3419. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  3420. document.getElementById('nat-modal-id').value = r.id;
  3421. document.getElementById('nat-modal-enabled').checked = !r.disabled;
  3422. document.getElementById('nat-modal-comment').value = r.comment || '';
  3423. document.getElementById('nat-modal-chain').value = r.chain || 'srcnat';
  3424. document.getElementById('nat-modal-action').value = r.action || 'masquerade';
  3425. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  3426. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  3427. document.getElementById('nat-modal-log').checked = !!r.log;
  3428. populateInterfaceSelect('nat-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  3429. populateInterfaceSelect('nat-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  3430. populateAddressListSelect('nat-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  3431. populateAddressListSelect('nat-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  3432. populateGeoIPSelect('nat-val-srcgeo', r.src_geoip || '');
  3433. populateGeoIPSelect('nat-val-dstgeo', r.dst_geoip || '');
  3434. setNATFieldVal('src', r.src_address, true);
  3435. setNATFieldVal('dst', r.dst_address, true);
  3436. setNATFieldVal('srclist', r.src_address_list, true);
  3437. setNATFieldVal('dstlist', r.dst_address_list, true);
  3438. setNATFieldVal('srcgeo', r.src_geoip, true);
  3439. setNATFieldVal('dstgeo', r.dst_geoip, true);
  3440. if (r.protocol && r.protocol !== 'all') {
  3441. setNATFieldVal('proto', r.protocol, true);
  3442. } else {
  3443. toggleNATField('proto', false);
  3444. }
  3445. setNATFieldVal('sport', r.src_port, true);
  3446. setNATFieldVal('dport', r.dst_port, true);
  3447. setNATFieldVal('anyport', r.any_port, true);
  3448. setNATFieldVal('iniface', r.in_interface, true);
  3449. setNATFieldVal('outiface', r.out_interface, true);
  3450. setNATFieldVal('inifacelist', r.in_interface_list, true);
  3451. setNATFieldVal('outifacelist', r.out_interface_list, true);
  3452. setNATFieldVal('pktmark', r.packet_mark, true);
  3453. setNATFieldVal('connmark', r.connection_mark, true);
  3454. setNATFieldVal('routingmark', r.routing_mark, true);
  3455. setNATFieldVal('conntype', r.connection_type, false);
  3456. // Advanced tab fields
  3457. setNATFieldVal('layer7', r.layer7_protocol, false);
  3458. setNATFieldVal('content', r.content, false);
  3459. setNATFieldVal('connbytes', r.connection_bytes, false);
  3460. setNATFieldVal('connrate', r.connection_rate, false);
  3461. setNATFieldVal('pcc', r.pcc, false);
  3462. setNATFieldVal('srcmac', r.src_mac_address, true);
  3463. setNATFieldVal('outbridgeport', r.out_bridge_port, false);
  3464. setNATFieldVal('inbridgeport', r.in_bridge_port, false);
  3465. setNATFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  3466. setNATFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  3467. setNATFieldVal('ipsec', r.ipsec_policy, false);
  3468. setNATFieldVal('ingresspriority', r.ingress_priority, false);
  3469. setNATFieldVal('priority', r.priority, false);
  3470. setNATFieldVal('dscp', r.dscp, false);
  3471. setNATFieldVal('tcpmss', r.tcp_mss, false);
  3472. if (r.tos) {
  3473. const tosEl = document.getElementById('nat-val-tos');
  3474. if (tosEl) tosEl.value = r.tos;
  3475. }
  3476. setNATFieldVal('pktsize', r.packet_size, false);
  3477. setNATFieldVal('random', r.random, false);
  3478. setNATFieldVal('icmpoptions', r.icmp_options, false);
  3479. setNATFieldVal('ipv4options', r.ipv4_options, false);
  3480. setNATFieldVal('ttl', r.ttl, false);
  3481. // Extra tab fields
  3482. setNATFieldVal('time', r.time, false);
  3483. if (r.days) {
  3484. toggleNATField('days', true);
  3485. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3486. const chk = document.getElementById(`nat-day-${d}`);
  3487. if (chk) chk.checked = r.days.includes(d);
  3488. });
  3489. } else {
  3490. toggleNATField('days', false);
  3491. }
  3492. setNATFieldVal('limit', r.limit, false);
  3493. setNATFieldVal('dstlimit', r.dst_limit, false);
  3494. setNATFieldVal('psd', r.psd, false);
  3495. // Action fields
  3496. if (r.jump_target) {
  3497. const jtEl = document.getElementById('nat-modal-jumptarget');
  3498. if (jtEl) jtEl.value = r.jump_target;
  3499. }
  3500. if (r.address_list) {
  3501. const alEl = document.getElementById('nat-modal-action-addrlist');
  3502. if (alEl) alEl.value = r.address_list;
  3503. }
  3504. if (r.address_list_timeout) {
  3505. const toEl = document.getElementById('nat-modal-action-timeout');
  3506. if (toEl) toEl.value = r.address_list_timeout;
  3507. }
  3508. setNATFieldVal('logprefix', r.log_prefix, false);
  3509. // Statistics
  3510. const bEl = document.getElementById('nat-stat-bytes');
  3511. const pEl = document.getElementById('nat-stat-packets');
  3512. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  3513. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  3514. state.natLastBytes = r.bytes || 0;
  3515. state.natLastPackets = r.packets || 0;
  3516. state.natLastTimestamp = Date.now();
  3517. state.natStatRateHistory = new Array(30).fill(0);
  3518. state.natStatPktHistory = new Array(30).fill(0);
  3519. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  3520. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  3521. toggleNATActionFields();
  3522. document.getElementById('nat-modal').classList.remove('hidden');
  3523. }
  3524. function closeNATModal() {
  3525. stopNATStatPolling();
  3526. document.getElementById('nat-modal').classList.add('hidden');
  3527. }
  3528. function copyNATRule() {
  3529. document.getElementById('nat-modal-id').value = '';
  3530. const badge = document.getElementById('nat-modal-badge');
  3531. if (badge) badge.innerText = 'New...';
  3532. showToast('Rule Cloned', 'Ready to save as a new NAT rule copy', 'info');
  3533. }
  3534. function resetCurrentNATRuleCounters() {
  3535. state.natStatRateHistory = new Array(30).fill(0);
  3536. state.natStatPktHistory = new Array(30).fill(0);
  3537. state.natLastBytes = 0;
  3538. state.natLastPackets = 0;
  3539. state.natLastTimestamp = Date.now();
  3540. const bEl = document.getElementById('nat-stat-bytes');
  3541. const pEl = document.getElementById('nat-stat-packets');
  3542. const rEl = document.getElementById('nat-stat-rate');
  3543. const prEl = document.getElementById('nat-stat-pktrate');
  3544. if (bEl) bEl.value = '0 B';
  3545. if (pEl) pEl.value = '0';
  3546. if (rEl) rEl.value = '0 bps';
  3547. if (prEl) prEl.value = '0 p/s';
  3548. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  3549. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  3550. showToast('Counters Reset', 'NAT rule counter display reset to 0', 'info');
  3551. }
  3552. async function applyNATRule(closeAfter = false) {
  3553. const id = document.getElementById('nat-modal-id').value;
  3554. const chain = document.getElementById('nat-modal-chain').value;
  3555. const action = document.getElementById('nat-modal-action').value;
  3556. const comment = document.getElementById('nat-modal-comment').value.trim();
  3557. const enabled = document.getElementById('nat-modal-enabled').checked;
  3558. const src = getNATFieldVal('src', true);
  3559. const dst = getNATFieldVal('dst', true);
  3560. const srclist = getNATFieldVal('srclist', true);
  3561. const dstlist = getNATFieldVal('dstlist', true);
  3562. const srcgeo = getNATFieldVal('srcgeo', true);
  3563. const dstgeo = getNATFieldVal('dstgeo', true);
  3564. const proto = getNATFieldVal('proto', true);
  3565. const sport = getNATFieldVal('sport', true);
  3566. const dport = getNATFieldVal('dport', true);
  3567. const anyport = getNATFieldVal('anyport', true);
  3568. const iniface = getNATFieldVal('iniface', true);
  3569. const outiface = getNATFieldVal('outiface', true);
  3570. const inifacelist = getNATFieldVal('inifacelist', true);
  3571. const outifacelist = getNATFieldVal('outifacelist', true);
  3572. const pktmark = getNATFieldVal('pktmark', true);
  3573. const connmark = getNATFieldVal('connmark', true);
  3574. const routingmark = getNATFieldVal('routingmark', true);
  3575. const conntype = getNATFieldVal('conntype', false);
  3576. const usesAddr = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(action);
  3577. const usesPort = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat', 'redirect', 'masquerade'].includes(action);
  3578. const payload = {
  3579. id,
  3580. chain,
  3581. action,
  3582. to_addresses: usesAddr ? (document.getElementById('nat-modal-toaddr')?.value.trim() || '') : '',
  3583. to_ports: usesPort ? (document.getElementById('nat-modal-toport')?.value.trim() || '') : '',
  3584. protocol: proto || 'all',
  3585. src_address: src,
  3586. dst_address: dst,
  3587. src_port: sport,
  3588. dst_port: dport,
  3589. any_port: anyport,
  3590. in_interface: iniface,
  3591. out_interface: outiface,
  3592. in_interface_list: inifacelist,
  3593. out_interface_list: outifacelist,
  3594. packet_mark: pktmark,
  3595. connection_mark: connmark,
  3596. routing_mark: routingmark,
  3597. connection_type: conntype,
  3598. src_address_list: srclist,
  3599. dst_address_list: dstlist,
  3600. src_geoip: srcgeo,
  3601. dst_geoip: dstgeo,
  3602. comment,
  3603. disabled: !enabled,
  3604. // Advanced tab
  3605. layer7_protocol: getNATFieldVal('layer7', false),
  3606. content: getNATFieldVal('content', false),
  3607. connection_bytes: getNATFieldVal('connbytes', false),
  3608. connection_rate: getNATFieldVal('connrate', false),
  3609. pcc: getNATFieldVal('pcc', false),
  3610. src_mac_address: getNATFieldVal('srcmac', true),
  3611. out_bridge_port: getNATFieldVal('outbridgeport', false),
  3612. in_bridge_port: getNATFieldVal('inbridgeport', false),
  3613. in_bridge_port_list: getNATFieldVal('inbridgeportlist', false),
  3614. out_bridge_port_list: getNATFieldVal('outbridgeportlist', false),
  3615. ipsec_policy: getNATFieldVal('ipsec', false),
  3616. ingress_priority: getNATFieldVal('ingresspriority', false),
  3617. priority: getNATFieldVal('priority', false),
  3618. dscp: getNATFieldVal('dscp', false),
  3619. tcp_mss: getNATFieldVal('tcpmss', false),
  3620. tos: document.getElementById('nat-val-tos')?.value || '',
  3621. packet_size: getNATFieldVal('pktsize', false),
  3622. random: getNATFieldVal('random', false),
  3623. icmp_options: getNATFieldVal('icmpoptions', false),
  3624. ipv4_options: getNATFieldVal('ipv4options', false),
  3625. ttl: getNATFieldVal('ttl', false),
  3626. // Extra tab
  3627. time: getNATFieldVal('time', false),
  3628. limit: getNATFieldVal('limit', false),
  3629. dst_limit: getNATFieldVal('dstlimit', false),
  3630. psd: getNATFieldVal('psd', false),
  3631. // Action tab
  3632. jump_target: action === 'jump' ? (document.getElementById('nat-modal-jumptarget')?.value || '') : '',
  3633. address_list: action.includes('address') ? (document.getElementById('nat-modal-action-addrlist')?.value || '') : '',
  3634. address_list_timeout: action.includes('address') ? (document.getElementById('nat-modal-action-timeout')?.value || '') : '',
  3635. log: document.getElementById('nat-modal-log')?.checked || false,
  3636. log_prefix: getNATFieldVal('logprefix', false)
  3637. };
  3638. try {
  3639. const res = await fetch(`${API_BASE}/firewall/nat`, {
  3640. method: 'POST',
  3641. headers: { 'Content-Type': 'application/json' },
  3642. body: JSON.stringify(payload)
  3643. });
  3644. if (res.ok) {
  3645. const data = await res.json();
  3646. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  3647. loadFirewall(false);
  3648. if (closeAfter) {
  3649. closeNATModal();
  3650. } else {
  3651. if (data.id) {
  3652. document.getElementById('nat-modal-id').value = data.id;
  3653. const badge = document.getElementById('nat-modal-badge');
  3654. if (badge) badge.innerText = `#${data.id}`;
  3655. }
  3656. }
  3657. } else {
  3658. const err = await res.json();
  3659. showToast('Error', err.message || 'Failed to save rule', 'error');
  3660. }
  3661. } catch (err) {
  3662. showToast('Error', err.message, 'error');
  3663. }
  3664. }
  3665. function submitSaveNATRule(e) {
  3666. if (e && e.preventDefault) e.preventDefault();
  3667. return applyNATRule(true);
  3668. }
  3669. function startNATStatPolling() {
  3670. stopNATStatPolling();
  3671. pollNATRuleStats();
  3672. state.natStatInterval = setInterval(pollNATRuleStats, 1000);
  3673. }
  3674. function stopNATStatPolling() {
  3675. if (state.natStatInterval) {
  3676. clearInterval(state.natStatInterval);
  3677. state.natStatInterval = null;
  3678. }
  3679. }
  3680. async function pollNATRuleStats() {
  3681. const id = document.getElementById('nat-modal-id')?.value;
  3682. if (!id) {
  3683. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory || new Array(30).fill(0), 'bps', 'nat-stat-legend-rate');
  3684. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory || new Array(30).fill(0), 'p/s', 'nat-stat-legend-pktrate');
  3685. return;
  3686. }
  3687. try {
  3688. const res = await fetch(`${API_BASE}/firewall/nat`);
  3689. if (!res.ok) return;
  3690. const rules = await res.json();
  3691. const r = rules.find(x => x.id === id);
  3692. if (!r) return;
  3693. const now = Date.now();
  3694. const dt = Math.max(0.2, (now - (state.natLastTimestamp || now)) / 1000);
  3695. state.natLastTimestamp = now;
  3696. const curBytes = r.bytes || 0;
  3697. const curPackets = r.packets || 0;
  3698. const deltaBytes = Math.max(0, curBytes - (state.natLastBytes || curBytes));
  3699. const deltaPkts = Math.max(0, curPackets - (state.natLastPackets || curPackets));
  3700. state.natLastBytes = curBytes;
  3701. state.natLastPackets = curPackets;
  3702. const rateBps = Math.round((deltaBytes * 8) / dt);
  3703. const ratePkt = Math.round(deltaPkts / dt);
  3704. if (!state.natStatRateHistory) state.natStatRateHistory = new Array(30).fill(0);
  3705. if (!state.natStatPktHistory) state.natStatPktHistory = new Array(30).fill(0);
  3706. state.natStatRateHistory.push(rateBps);
  3707. if (state.natStatRateHistory.length > 30) state.natStatRateHistory.shift();
  3708. state.natStatPktHistory.push(ratePkt);
  3709. if (state.natStatPktHistory.length > 30) state.natStatPktHistory.shift();
  3710. const bEl = document.getElementById('nat-stat-bytes');
  3711. const pEl = document.getElementById('nat-stat-packets');
  3712. const rEl = document.getElementById('nat-stat-rate');
  3713. const prEl = document.getElementById('nat-stat-pktrate');
  3714. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  3715. if (pEl) pEl.value = curPackets.toLocaleString();
  3716. if (rEl) rEl.value = formatBps(rateBps);
  3717. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  3718. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  3719. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  3720. } catch (e) {
  3721. console.error('Error polling NAT rule stats', e);
  3722. }
  3723. }
  3724. async function moveNATRule(id, dir) {
  3725. try {
  3726. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  3727. method: 'POST',
  3728. headers: { 'Content-Type': 'application/json' },
  3729. body: JSON.stringify({ direction: dir })
  3730. });
  3731. if (res.ok) loadFirewall(false);
  3732. } catch (err) {
  3733. showToast('Error', err.message, 'error');
  3734. }
  3735. }
  3736. async function toggleNATRuleState(id, disabled) {
  3737. try {
  3738. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  3739. method: 'POST',
  3740. headers: { 'Content-Type': 'application/json' },
  3741. body: JSON.stringify({ disabled })
  3742. });
  3743. if (res.ok) loadFirewall(false);
  3744. } catch (err) {
  3745. showToast('Error', err.message, 'error');
  3746. }
  3747. }
  3748. async function deleteNATRule(id) {
  3749. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  3750. try {
  3751. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3752. if (res.ok) {
  3753. showToast('Deleted', 'NAT rule removed', 'success');
  3754. loadFirewall(false);
  3755. }
  3756. } catch (err) {
  3757. showToast('Error', err.message, 'error');
  3758. }
  3759. }
  3760. // ----------------- Mangle Rules -----------------
  3761. function renderMangleRules() {
  3762. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  3763. const tbody = document.getElementById('mangle-table-body');
  3764. const empty = document.getElementById('mangle-empty');
  3765. if (!tbody) return;
  3766. tbody.innerHTML = '';
  3767. const rules = (state.mangleRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  3768. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  3769. if (rules.length === 0) {
  3770. empty?.classList.remove('hidden');
  3771. return;
  3772. }
  3773. empty?.classList.add('hidden');
  3774. rules.forEach((r, idx) => {
  3775. const tr = document.createElement('tr');
  3776. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  3777. let markVal = '<span class="text-slate-500">-</span>';
  3778. if (r.new_connection_mark) markVal = `<span class="text-cyan-300 font-mono font-bold">${r.new_connection_mark}</span>`;
  3779. else if (r.new_routing_mark) markVal = `<span class="text-amber-300 font-mono font-bold">${r.new_routing_mark}</span>`;
  3780. else if (r.new_packet_mark) markVal = `<span class="text-emerald-300 font-mono font-bold">${r.new_packet_mark}</span>`;
  3781. else if (r.new_mss) markVal = `<span class="text-sky-300 font-mono font-bold">mss:${r.new_mss}</span>`;
  3782. else if (r.new_dscp) markVal = `<span class="text-purple-300 font-mono font-bold">dscp:${r.new_dscp}</span>`;
  3783. else if (r.new_ttl) markVal = `<span class="text-blue-300 font-mono font-bold">ttl:${r.new_ttl}</span>`;
  3784. else if (r.new_priority) markVal = `<span class="text-indigo-300 font-mono font-bold">prio:${r.new_priority}</span>`;
  3785. else if (r.route) markVal = `<span class="text-orange-300 font-mono font-bold">route:${r.route}</span>`;
  3786. else if (r.sniff_target) markVal = `<span class="text-pink-300 font-mono font-bold">sniff:${r.sniff_target}</span>`;
  3787. else if (r.action === 'jump') markVal = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  3788. 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>`;
  3789. else if (r.action === 'log') markVal = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  3790. tr.innerHTML = `
  3791. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  3792. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  3793. <td class="py-2.5 px-3 font-bold text-purple-400">${r.chain}</td>
  3794. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  3795. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  3796. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  3797. <td class="py-2.5 px-3 font-mono text-xs">${markVal}</td>
  3798. <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>
  3799. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  3800. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  3801. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  3802. </td>
  3803. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  3804. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3805. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  3806. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  3807. <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>
  3808. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3809. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3810. </td>
  3811. `;
  3812. tbody.appendChild(tr);
  3813. });
  3814. }
  3815. // ==================== FIREWALL MANGLE MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  3816. function switchMangleRuleTab(tab) {
  3817. state.activeMangleRuleTab = tab;
  3818. document.querySelectorAll('.mangle-rule-tab-btn').forEach(btn => {
  3819. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  3820. btn.classList.add('text-slate-400', 'border-transparent');
  3821. });
  3822. const activeBtn = document.getElementById(`mangle-tab-btn-${tab}`);
  3823. if (activeBtn) {
  3824. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  3825. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  3826. }
  3827. document.querySelectorAll('.mangle-rule-pane').forEach(p => p.classList.add('hidden'));
  3828. const activePane = document.getElementById(`mangle-pane-${tab}`);
  3829. if (activePane) activePane.classList.remove('hidden');
  3830. if (tab === 'statistics') {
  3831. startMangleStatPolling();
  3832. } else {
  3833. stopMangleStatPolling();
  3834. }
  3835. }
  3836. function toggleMangleField(fieldKey, expand) {
  3837. const plusBtn = document.getElementById(`mangle-plus-${fieldKey}`);
  3838. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  3839. if (!plusBtn || !fieldBox) return;
  3840. if (expand) {
  3841. plusBtn.classList.add('hidden');
  3842. fieldBox.classList.remove('hidden');
  3843. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  3844. if (valInput) valInput.focus();
  3845. } else {
  3846. fieldBox.classList.add('hidden');
  3847. plusBtn.classList.remove('hidden');
  3848. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  3849. if (valInput) {
  3850. if (valInput.tagName === 'SELECT') {
  3851. valInput.selectedIndex = 0;
  3852. } else {
  3853. valInput.value = '';
  3854. }
  3855. }
  3856. const invInput = document.getElementById(`mangle-inv-${fieldKey}`);
  3857. if (invInput) invInput.checked = false;
  3858. if (fieldKey === 'cs') {
  3859. ['mangle-modal-cs-established', 'mangle-modal-cs-related', 'mangle-modal-cs-new', 'mangle-modal-cs-invalid', 'mangle-modal-cs-untracked'].forEach(id => {
  3860. const el = document.getElementById(id);
  3861. if (el) el.checked = false;
  3862. });
  3863. }
  3864. if (fieldKey === 'natstate') {
  3865. ['mangle-modal-nat-srcnat', 'mangle-modal-nat-dstnat'].forEach(id => {
  3866. const el = document.getElementById(id);
  3867. if (el) el.checked = false;
  3868. });
  3869. }
  3870. }
  3871. }
  3872. function setMangleFieldVal(fieldKey, value, hasInvert = false) {
  3873. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  3874. toggleMangleField(fieldKey, true);
  3875. let strVal = String(value);
  3876. if (hasInvert) {
  3877. const inv = strVal.startsWith('!');
  3878. if (inv) strVal = strVal.slice(1);
  3879. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  3880. if (invEl) invEl.checked = inv;
  3881. }
  3882. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  3883. if (valEl) valEl.value = strVal;
  3884. } else {
  3885. toggleMangleField(fieldKey, false);
  3886. }
  3887. }
  3888. function getMangleFieldVal(fieldKey, hasInvert = false) {
  3889. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  3890. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3891. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  3892. let v = valEl ? valEl.value.trim() : '';
  3893. if (!v) return '';
  3894. if (hasInvert) {
  3895. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  3896. if (invEl && invEl.checked) {
  3897. v = '!' + v.replace(/^!/, '');
  3898. }
  3899. }
  3900. return v;
  3901. }
  3902. function toggleMaximizeMangleModal() {
  3903. const win = document.getElementById('mangle-modal-window');
  3904. if (!win) return;
  3905. if (win.classList.contains('max-w-[720px]')) {
  3906. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3907. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3908. } else {
  3909. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3910. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3911. }
  3912. }
  3913. function toggleMangleActionFields() {
  3914. const act = document.getElementById('mangle-modal-action')?.value || 'mark-connection';
  3915. // Hide all dynamic rows first
  3916. ['newconnmark', 'newroutingmark', 'newpktmark', 'newmss', 'newdscp', 'newttl', 'newpriority', 'route', 'sniff', 'passthrough'].forEach(id => {
  3917. const el = document.getElementById(`mangle-row-${id}`);
  3918. if (el) el.classList.add('hidden');
  3919. });
  3920. const jumpBox = document.getElementById('mangle-action-jump-box');
  3921. const addrBox = document.getElementById('mangle-action-addrlist-box');
  3922. if (jumpBox) jumpBox.classList.add('hidden');
  3923. if (addrBox) addrBox.classList.add('hidden');
  3924. // Activate matching rows
  3925. if (act === 'mark-connection') {
  3926. document.getElementById('mangle-row-newconnmark')?.classList.remove('hidden');
  3927. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  3928. } else if (act === 'mark-routing') {
  3929. document.getElementById('mangle-row-newroutingmark')?.classList.remove('hidden');
  3930. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  3931. } else if (act === 'mark-packet') {
  3932. document.getElementById('mangle-row-newpktmark')?.classList.remove('hidden');
  3933. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  3934. } else if (act === 'change-mss') {
  3935. document.getElementById('mangle-row-newmss')?.classList.remove('hidden');
  3936. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  3937. } else if (act === 'change-dscp') {
  3938. document.getElementById('mangle-row-newdscp')?.classList.remove('hidden');
  3939. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  3940. } else if (act === 'change-ttl') {
  3941. document.getElementById('mangle-row-newttl')?.classList.remove('hidden');
  3942. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  3943. } else if (act === 'set-priority') {
  3944. document.getElementById('mangle-row-newpriority')?.classList.remove('hidden');
  3945. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  3946. } else if (act === 'route') {
  3947. document.getElementById('mangle-row-route')?.classList.remove('hidden');
  3948. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  3949. } else if (act === 'sniff-pc' || act === 'sniff-tzsp') {
  3950. document.getElementById('mangle-row-sniff')?.classList.remove('hidden');
  3951. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  3952. } else if (act === 'clear-df' || act === 'strip-ipv4-options') {
  3953. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  3954. } else if (act === 'jump') {
  3955. if (jumpBox) jumpBox.classList.remove('hidden');
  3956. } else if (act.includes('address-list') || act.includes('address list')) {
  3957. if (addrBox) addrBox.classList.remove('hidden');
  3958. }
  3959. if (act === 'log') {
  3960. const logEl = document.getElementById('mangle-modal-log');
  3961. if (logEl) logEl.checked = true;
  3962. toggleMangleField('logprefix', true);
  3963. }
  3964. }
  3965. function toggleMangleLogPrefix() {
  3966. const isLog = document.getElementById('mangle-modal-log')?.checked;
  3967. toggleMangleField('logprefix', !!isLog);
  3968. }
  3969. const allMangleFieldKeys = [
  3970. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  3971. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  3972. 'routingmark', 'conntype', 'cs', 'natstate',
  3973. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  3974. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  3975. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  3976. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  3977. 'nth', 'connlimit', 'srcaddrtype', 'dstaddrtype', 'hotspot', 'ipfragment',
  3978. 'limit', 'dstlimit', 'time', 'psd', 'logprefix'
  3979. ];
  3980. function openAddMangleModal() {
  3981. switchMangleRuleTab('general');
  3982. const badge = document.getElementById('mangle-modal-badge');
  3983. if (badge) badge.innerText = 'New...';
  3984. document.getElementById('mangle-modal-id').value = '';
  3985. document.getElementById('mangle-modal-enabled').checked = true;
  3986. document.getElementById('mangle-modal-comment').value = '';
  3987. document.getElementById('mangle-modal-chain').value = 'prerouting';
  3988. document.getElementById('mangle-modal-action').value = 'mark-connection';
  3989. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = '';
  3990. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = '';
  3991. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = '';
  3992. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = '';
  3993. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = '';
  3994. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = '';
  3995. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = '';
  3996. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = '';
  3997. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = '';
  3998. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = '';
  3999. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = '';
  4000. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = '';
  4001. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = true;
  4002. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = false;
  4003. populateInterfaceSelect('mangle-val-iniface');
  4004. populateInterfaceSelect('mangle-val-outiface');
  4005. populateAddressListSelect('mangle-val-srclist');
  4006. populateAddressListSelect('mangle-val-dstlist');
  4007. populateGeoIPSelect('mangle-val-srcgeo');
  4008. populateGeoIPSelect('mangle-val-dstgeo');
  4009. allMangleFieldKeys.forEach(k => toggleMangleField(k, false));
  4010. resetCurrentMangleRuleCounters();
  4011. toggleMangleActionFields();
  4012. document.getElementById('mangle-modal').classList.remove('hidden');
  4013. }
  4014. function openEditMangleModal(id) {
  4015. const r = (state.mangleRules || []).find(rule => rule.id === id);
  4016. if (!r) return;
  4017. switchMangleRuleTab('general');
  4018. const badge = document.getElementById('mangle-modal-badge');
  4019. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4020. document.getElementById('mangle-modal-id').value = r.id;
  4021. document.getElementById('mangle-modal-enabled').checked = !r.disabled;
  4022. document.getElementById('mangle-modal-comment').value = r.comment || '';
  4023. document.getElementById('mangle-modal-chain').value = r.chain || 'prerouting';
  4024. document.getElementById('mangle-modal-action').value = r.action || 'mark-connection';
  4025. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = r.new_connection_mark || '';
  4026. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = r.new_routing_mark || '';
  4027. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = r.new_packet_mark || '';
  4028. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = r.new_mss || '';
  4029. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = r.new_dscp != null ? r.new_dscp : '';
  4030. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = r.new_ttl || '';
  4031. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = r.new_priority || '';
  4032. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = r.route || '';
  4033. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = r.sniff_target || '';
  4034. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = r.jump_target || '';
  4035. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = r.address_list || '';
  4036. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = r.address_list_timeout || '';
  4037. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  4038. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = !!r.log;
  4039. populateInterfaceSelect('mangle-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  4040. populateInterfaceSelect('mangle-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  4041. populateAddressListSelect('mangle-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  4042. populateAddressListSelect('mangle-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  4043. populateGeoIPSelect('mangle-val-srcgeo', r.src_geoip || '');
  4044. populateGeoIPSelect('mangle-val-dstgeo', r.dst_geoip || '');
  4045. setMangleFieldVal('src', r.src_address, true);
  4046. setMangleFieldVal('dst', r.dst_address, true);
  4047. setMangleFieldVal('srclist', r.src_address_list, true);
  4048. setMangleFieldVal('dstlist', r.dst_address_list, true);
  4049. setMangleFieldVal('srcgeo', r.src_geoip, true);
  4050. setMangleFieldVal('dstgeo', r.dst_geoip, true);
  4051. if (r.protocol && r.protocol !== 'all') {
  4052. setMangleFieldVal('proto', r.protocol, true);
  4053. } else {
  4054. toggleMangleField('proto', false);
  4055. }
  4056. setMangleFieldVal('sport', r.src_port, true);
  4057. setMangleFieldVal('dport', r.dst_port, true);
  4058. setMangleFieldVal('anyport', r.any_port, true);
  4059. setMangleFieldVal('iniface', r.in_interface, true);
  4060. setMangleFieldVal('outiface', r.out_interface, true);
  4061. setMangleFieldVal('inifacelist', r.in_interface_list, true);
  4062. setMangleFieldVal('outifacelist', r.out_interface_list, true);
  4063. setMangleFieldVal('pktmark', r.packet_mark, true);
  4064. setMangleFieldVal('connmark', r.connection_mark, true);
  4065. setMangleFieldVal('routingmark', r.routing_mark, true);
  4066. setMangleFieldVal('conntype', r.connection_type, false);
  4067. // Connection State
  4068. const states = r.connection_state || [];
  4069. if (states.length > 0) {
  4070. toggleMangleField('cs', true);
  4071. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  4072. const el = document.getElementById(`mangle-modal-cs-${s}`);
  4073. if (el) el.checked = states.includes(s);
  4074. });
  4075. } else {
  4076. toggleMangleField('cs', false);
  4077. }
  4078. // Connection NAT State
  4079. const natStates = r.connection_nat_state || [];
  4080. if (natStates.length > 0) {
  4081. toggleMangleField('natstate', true);
  4082. ['srcnat', 'dstnat'].forEach(s => {
  4083. const el = document.getElementById(`mangle-modal-nat-${s}`);
  4084. if (el) el.checked = natStates.includes(s);
  4085. });
  4086. } else {
  4087. toggleMangleField('natstate', false);
  4088. }
  4089. // Advanced tab fields
  4090. setMangleFieldVal('layer7', r.layer7_protocol, false);
  4091. setMangleFieldVal('content', r.content, false);
  4092. setMangleFieldVal('connbytes', r.connection_bytes, false);
  4093. setMangleFieldVal('connrate', r.connection_rate, false);
  4094. setMangleFieldVal('pcc', r.pcc, false);
  4095. setMangleFieldVal('srcmac', r.src_mac_address, true);
  4096. setMangleFieldVal('outbridgeport', r.out_bridge_port, false);
  4097. setMangleFieldVal('inbridgeport', r.in_bridge_port, false);
  4098. setMangleFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  4099. setMangleFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  4100. setMangleFieldVal('ipsec', r.ipsec_policy, false);
  4101. setMangleFieldVal('tlshost', r.tls_host, false);
  4102. setMangleFieldVal('ingresspriority', r.ingress_priority, false);
  4103. setMangleFieldVal('priority', r.priority, false);
  4104. setMangleFieldVal('dscp', r.dscp, false);
  4105. setMangleFieldVal('tcpmss', r.tcp_mss, false);
  4106. if (r.tos) {
  4107. const tosEl = document.getElementById('mangle-val-tos');
  4108. if (tosEl) tosEl.value = r.tos;
  4109. }
  4110. setMangleFieldVal('pktsize', r.packet_size, false);
  4111. setMangleFieldVal('random', r.random, false);
  4112. setMangleFieldVal('tcpflags', r.tcp_flags, false);
  4113. setMangleFieldVal('icmpoptions', r.icmp_options, false);
  4114. setMangleFieldVal('ipv4options', r.ipv4_options, false);
  4115. setMangleFieldVal('ttl', r.ttl, false);
  4116. // Extra tab fields
  4117. setMangleFieldVal('nth', r.nth, false);
  4118. setMangleFieldVal('connlimit', r.connection_limit, false);
  4119. setMangleFieldVal('srcaddrtype', r.src_address_type, false);
  4120. setMangleFieldVal('dstaddrtype', r.dst_address_type, false);
  4121. setMangleFieldVal('hotspot', r.hotspot, false);
  4122. setMangleFieldVal('ipfragment', r.ip_fragment, false);
  4123. setMangleFieldVal('limit', r.limit, false);
  4124. setMangleFieldVal('dstlimit', r.dst_limit, false);
  4125. setMangleFieldVal('time', r.time, false);
  4126. setMangleFieldVal('psd', r.psd, false);
  4127. // Action fields
  4128. if (r.jump_target) {
  4129. const jtEl = document.getElementById('mangle-modal-jumptarget');
  4130. if (jtEl) jtEl.value = r.jump_target;
  4131. }
  4132. if (r.address_list) {
  4133. const alEl = document.getElementById('mangle-modal-action-addrlist');
  4134. if (alEl) alEl.value = r.address_list;
  4135. }
  4136. if (r.address_list_timeout) {
  4137. const toEl = document.getElementById('mangle-modal-action-timeout');
  4138. if (toEl) toEl.value = r.address_list_timeout;
  4139. }
  4140. setMangleFieldVal('logprefix', r.log_prefix, false);
  4141. // Statistics
  4142. const bEl = document.getElementById('mangle-stat-bytes');
  4143. const pEl = document.getElementById('mangle-stat-packets');
  4144. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  4145. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  4146. state.mangleLastBytes = r.bytes || 0;
  4147. state.mangleLastPackets = r.packets || 0;
  4148. state.mangleLastTimestamp = Date.now();
  4149. state.mangleStatRateHistory = new Array(30).fill(0);
  4150. state.mangleStatPktHistory = new Array(30).fill(0);
  4151. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4152. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4153. toggleMangleActionFields();
  4154. document.getElementById('mangle-modal').classList.remove('hidden');
  4155. }
  4156. function closeMangleModal() {
  4157. stopMangleStatPolling();
  4158. document.getElementById('mangle-modal').classList.add('hidden');
  4159. }
  4160. function copyMangleRule() {
  4161. document.getElementById('mangle-modal-id').value = '';
  4162. const badge = document.getElementById('mangle-modal-badge');
  4163. if (badge) badge.innerText = 'New...';
  4164. showToast('Rule Cloned', 'Ready to save as a new Mangle rule copy', 'info');
  4165. }
  4166. function resetCurrentMangleRuleCounters() {
  4167. state.mangleStatRateHistory = new Array(30).fill(0);
  4168. state.mangleStatPktHistory = new Array(30).fill(0);
  4169. state.mangleLastBytes = 0;
  4170. state.mangleLastPackets = 0;
  4171. state.mangleLastTimestamp = Date.now();
  4172. const bEl = document.getElementById('mangle-stat-bytes');
  4173. const pEl = document.getElementById('mangle-stat-packets');
  4174. const rEl = document.getElementById('mangle-stat-rate');
  4175. const prEl = document.getElementById('mangle-stat-pktrate');
  4176. if (bEl) bEl.value = '0 B';
  4177. if (pEl) pEl.value = '0';
  4178. if (rEl) rEl.value = '0 bps';
  4179. if (prEl) prEl.value = '0 p/s';
  4180. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4181. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4182. showToast('Counters Reset', 'Mangle rule counter display reset to 0', 'info');
  4183. }
  4184. async function applyMangleRule(closeAfter = false) {
  4185. const id = document.getElementById('mangle-modal-id').value;
  4186. const chain = document.getElementById('mangle-modal-chain').value;
  4187. const action = document.getElementById('mangle-modal-action').value;
  4188. const comment = document.getElementById('mangle-modal-comment').value.trim();
  4189. const enabled = document.getElementById('mangle-modal-enabled').checked;
  4190. const src = getMangleFieldVal('src', true);
  4191. const dst = getMangleFieldVal('dst', true);
  4192. const srclist = getMangleFieldVal('srclist', true);
  4193. const dstlist = getMangleFieldVal('dstlist', true);
  4194. const srcgeo = getMangleFieldVal('srcgeo', true);
  4195. const dstgeo = getMangleFieldVal('dstgeo', true);
  4196. const proto = getMangleFieldVal('proto', true);
  4197. const sport = getMangleFieldVal('sport', true);
  4198. const dport = getMangleFieldVal('dport', true);
  4199. const anyport = getMangleFieldVal('anyport', true);
  4200. const iniface = getMangleFieldVal('iniface', true);
  4201. const outiface = getMangleFieldVal('outiface', true);
  4202. const inifacelist = getMangleFieldVal('inifacelist', true);
  4203. const outifacelist = getMangleFieldVal('outifacelist', true);
  4204. const pktmark = getMangleFieldVal('pktmark', true);
  4205. const connmark = getMangleFieldVal('connmark', true);
  4206. const routingmark = getMangleFieldVal('routingmark', true);
  4207. const conntype = getMangleFieldVal('conntype', false);
  4208. const states = [];
  4209. const csBox = document.getElementById('mangle-field-cs');
  4210. if (csBox && !csBox.classList.contains('hidden')) {
  4211. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  4212. if (document.getElementById(`mangle-modal-cs-${s}`)?.checked) states.push(s);
  4213. });
  4214. }
  4215. const natStates = [];
  4216. const natBox = document.getElementById('mangle-field-natstate');
  4217. if (natBox && !natBox.classList.contains('hidden')) {
  4218. ['srcnat', 'dstnat'].forEach(s => {
  4219. if (document.getElementById(`mangle-modal-nat-${s}`)?.checked) natStates.push(s);
  4220. });
  4221. }
  4222. const payload = {
  4223. id,
  4224. chain,
  4225. action,
  4226. protocol: proto || 'all',
  4227. src_address: src,
  4228. dst_address: dst,
  4229. src_port: sport,
  4230. dst_port: dport,
  4231. any_port: anyport,
  4232. in_interface: iniface,
  4233. out_interface: outiface,
  4234. in_interface_list: inifacelist,
  4235. out_interface_list: outifacelist,
  4236. packet_mark: pktmark,
  4237. connection_mark: connmark,
  4238. routing_mark: routingmark,
  4239. connection_type: conntype,
  4240. connection_state: states,
  4241. connection_nat_state: natStates,
  4242. src_address_list: srclist,
  4243. dst_address_list: dstlist,
  4244. src_geoip: srcgeo,
  4245. dst_geoip: dstgeo,
  4246. comment,
  4247. disabled: !enabled,
  4248. // Advanced tab
  4249. layer7_protocol: getMangleFieldVal('layer7', false),
  4250. content: getMangleFieldVal('content', false),
  4251. connection_bytes: getMangleFieldVal('connbytes', false),
  4252. connection_rate: getMangleFieldVal('connrate', false),
  4253. pcc: getMangleFieldVal('pcc', false),
  4254. src_mac_address: getMangleFieldVal('srcmac', true),
  4255. out_bridge_port: getMangleFieldVal('outbridgeport', false),
  4256. in_bridge_port: getMangleFieldVal('inbridgeport', false),
  4257. in_bridge_port_list: getMangleFieldVal('inbridgeportlist', false),
  4258. out_bridge_port_list: getMangleFieldVal('outbridgeportlist', false),
  4259. ipsec_policy: getMangleFieldVal('ipsec', false),
  4260. tls_host: getMangleFieldVal('tlshost', false),
  4261. ingress_priority: getMangleFieldVal('ingresspriority', false),
  4262. priority: getMangleFieldVal('priority', false),
  4263. dscp: getMangleFieldVal('dscp', false),
  4264. tcp_mss: getMangleFieldVal('tcpmss', false),
  4265. tos: document.getElementById('mangle-val-tos')?.value || '',
  4266. packet_size: getMangleFieldVal('pktsize', false),
  4267. random: getMangleFieldVal('random', false),
  4268. tcp_flags: getMangleFieldVal('tcpflags', false),
  4269. icmp_options: getMangleFieldVal('icmpoptions', false),
  4270. ipv4_options: getMangleFieldVal('ipv4options', false),
  4271. ttl: getMangleFieldVal('ttl', false),
  4272. // Extra tab
  4273. nth: getMangleFieldVal('nth', false),
  4274. connection_limit: getMangleFieldVal('connlimit', false),
  4275. src_address_type: getMangleFieldVal('srcaddrtype', false),
  4276. dst_address_type: getMangleFieldVal('dstaddrtype', false),
  4277. hotspot: getMangleFieldVal('hotspot', false),
  4278. ip_fragment: getMangleFieldVal('ipfragment', false),
  4279. limit: getMangleFieldVal('limit', false),
  4280. dst_limit: getMangleFieldVal('dstlimit', false),
  4281. time: getMangleFieldVal('time', false),
  4282. psd: getMangleFieldVal('psd', false),
  4283. // Action tab
  4284. new_connection_mark: action === 'mark-connection' ? (document.getElementById('mangle-modal-newconnmark')?.value.trim() || '') : '',
  4285. new_routing_mark: action === 'mark-routing' ? (document.getElementById('mangle-modal-newroutingmark')?.value.trim() || '') : '',
  4286. new_packet_mark: action === 'mark-packet' ? (document.getElementById('mangle-modal-newpktmark')?.value.trim() || '') : '',
  4287. new_mss: action === 'change-mss' ? (document.getElementById('mangle-modal-newmss')?.value.trim() || '') : '',
  4288. new_dscp: action === 'change-dscp' ? parseInt(document.getElementById('mangle-modal-newdscp')?.value || '0', 10) : 0,
  4289. new_ttl: action === 'change-ttl' ? (document.getElementById('mangle-modal-newttl')?.value.trim() || '') : '',
  4290. new_priority: action === 'set-priority' ? (document.getElementById('mangle-modal-newpriority')?.value.trim() || '') : '',
  4291. route: action === 'route' ? (document.getElementById('mangle-modal-route')?.value.trim() || '') : '',
  4292. sniff_target: (action === 'sniff-pc' || action === 'sniff-tzsp') ? (document.getElementById('mangle-modal-sniff')?.value.trim() || '') : '',
  4293. passthrough: document.getElementById('mangle-modal-passthrough')?.checked ?? true,
  4294. jump_target: action === 'jump' ? (document.getElementById('mangle-modal-jumptarget')?.value || '') : '',
  4295. address_list: action.includes('address') ? (document.getElementById('mangle-modal-action-addrlist')?.value || '') : '',
  4296. address_list_timeout: action.includes('address') ? (document.getElementById('mangle-modal-action-timeout')?.value || '') : '',
  4297. log: document.getElementById('mangle-modal-log')?.checked || false,
  4298. log_prefix: getMangleFieldVal('logprefix', false)
  4299. };
  4300. try {
  4301. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  4302. method: 'POST',
  4303. headers: { 'Content-Type': 'application/json' },
  4304. body: JSON.stringify(payload)
  4305. });
  4306. if (res.ok) {
  4307. const data = await res.json();
  4308. showToast('Mangle Rule Saved', 'Marking rule updated', 'success');
  4309. loadFirewall(false);
  4310. if (closeAfter) {
  4311. closeMangleModal();
  4312. } else {
  4313. if (data.id) {
  4314. document.getElementById('mangle-modal-id').value = data.id;
  4315. const badge = document.getElementById('mangle-modal-badge');
  4316. if (badge) badge.innerText = `#${data.id}`;
  4317. }
  4318. }
  4319. } else {
  4320. const err = await res.json();
  4321. showToast('Error', err.message || 'Failed to save mangle rule', 'error');
  4322. }
  4323. } catch (err) {
  4324. showToast('Error', err.message, 'error');
  4325. }
  4326. }
  4327. function submitSaveMangleRule(e) {
  4328. if (e && e.preventDefault) e.preventDefault();
  4329. return applyMangleRule(true);
  4330. }
  4331. function startMangleStatPolling() {
  4332. stopMangleStatPolling();
  4333. pollMangleRuleStats();
  4334. state.mangleStatInterval = setInterval(pollMangleRuleStats, 1000);
  4335. }
  4336. function stopMangleStatPolling() {
  4337. if (state.mangleStatInterval) {
  4338. clearInterval(state.mangleStatInterval);
  4339. state.mangleStatInterval = null;
  4340. }
  4341. }
  4342. async function pollMangleRuleStats() {
  4343. const id = document.getElementById('mangle-modal-id')?.value;
  4344. if (!id) {
  4345. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory || new Array(30).fill(0), 'bps', 'mangle-stat-legend-rate');
  4346. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory || new Array(30).fill(0), 'p/s', 'mangle-stat-legend-pktrate');
  4347. return;
  4348. }
  4349. try {
  4350. const res = await fetch(`${API_BASE}/firewall/mangle`);
  4351. if (!res.ok) return;
  4352. const rules = await res.json();
  4353. const r = rules.find(x => x.id === id);
  4354. if (!r) return;
  4355. const now = Date.now();
  4356. const dt = Math.max(0.2, (now - (state.mangleLastTimestamp || now)) / 1000);
  4357. state.mangleLastTimestamp = now;
  4358. const curBytes = r.bytes || 0;
  4359. const curPackets = r.packets || 0;
  4360. const deltaBytes = Math.max(0, curBytes - (state.mangleLastBytes || curBytes));
  4361. const deltaPkts = Math.max(0, curPackets - (state.mangleLastPackets || curPackets));
  4362. state.mangleLastBytes = curBytes;
  4363. state.mangleLastPackets = curPackets;
  4364. const rateBps = Math.round((deltaBytes * 8) / dt);
  4365. const ratePkt = Math.round(deltaPkts / dt);
  4366. if (!state.mangleStatRateHistory) state.mangleStatRateHistory = new Array(30).fill(0);
  4367. if (!state.mangleStatPktHistory) state.mangleStatPktHistory = new Array(30).fill(0);
  4368. state.mangleStatRateHistory.push(rateBps);
  4369. if (state.mangleStatRateHistory.length > 30) state.mangleStatRateHistory.shift();
  4370. state.mangleStatPktHistory.push(ratePkt);
  4371. if (state.mangleStatPktHistory.length > 30) state.mangleStatPktHistory.shift();
  4372. const bEl = document.getElementById('mangle-stat-bytes');
  4373. const pEl = document.getElementById('mangle-stat-packets');
  4374. const rEl = document.getElementById('mangle-stat-rate');
  4375. const prEl = document.getElementById('mangle-stat-pktrate');
  4376. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4377. if (pEl) pEl.value = curPackets.toLocaleString();
  4378. if (rEl) rEl.value = formatBps(rateBps);
  4379. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4380. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4381. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4382. } catch (e) {
  4383. console.error('Error polling Mangle rule stats', e);
  4384. }
  4385. }
  4386. async function moveMangleRule(id, dir) {
  4387. try {
  4388. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  4389. method: 'POST',
  4390. headers: { 'Content-Type': 'application/json' },
  4391. body: JSON.stringify({ direction: dir })
  4392. });
  4393. if (res.ok) loadFirewall(false);
  4394. } catch (err) {
  4395. showToast('Error', err.message, 'error');
  4396. }
  4397. }
  4398. async function toggleMangleRuleState(id, disabled) {
  4399. try {
  4400. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  4401. method: 'POST',
  4402. headers: { 'Content-Type': 'application/json' },
  4403. body: JSON.stringify({ disabled })
  4404. });
  4405. if (res.ok) loadFirewall(false);
  4406. } catch (err) {
  4407. showToast('Error', err.message, 'error');
  4408. }
  4409. }
  4410. async function deleteMangleRule(id) {
  4411. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  4412. try {
  4413. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4414. if (res.ok) {
  4415. showToast('Deleted', 'Mangle rule removed', 'success');
  4416. loadFirewall(false);
  4417. }
  4418. } catch (err) {
  4419. showToast('Error', err.message, 'error');
  4420. }
  4421. }
  4422. // ----------------- Address Lists -----------------
  4423. function renderAddressLists() {
  4424. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  4425. const tbody = document.getElementById('addrlist-table-body');
  4426. const empty = document.getElementById('addrlist-empty');
  4427. if (!tbody) return;
  4428. tbody.innerHTML = '';
  4429. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  4430. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries`;
  4431. // Update filter select
  4432. const sel = document.getElementById('addrlist-filter-name');
  4433. if (sel) {
  4434. const cur = sel.value;
  4435. sel.innerHTML = '<option value="">All Lists</option>';
  4436. const set = new Set((state.addressLists || []).map(a => a.name));
  4437. set.forEach(n => {
  4438. const opt = document.createElement('option');
  4439. opt.value = n;
  4440. opt.innerText = n;
  4441. if (n === cur) opt.selected = true;
  4442. sel.appendChild(opt);
  4443. });
  4444. }
  4445. if (entries.length === 0) {
  4446. empty?.classList.remove('hidden');
  4447. return;
  4448. }
  4449. empty?.classList.add('hidden');
  4450. entries.forEach((e, idx) => {
  4451. const tr = document.createElement('tr');
  4452. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
  4453. tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
  4454. tr.innerHTML = `
  4455. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  4456. <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>
  4457. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  4458. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  4459. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]">${e.comment || '-'}</td>
  4460. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  4461. <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>
  4462. <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
  4463. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4464. </td>
  4465. `;
  4466. tbody.appendChild(tr);
  4467. });
  4468. populateCommonAddrListDatalist();
  4469. }
  4470. function openAddAddrListModal() {
  4471. document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
  4472. document.getElementById('addrlist-modal-id').value = '';
  4473. document.getElementById('addrlist-modal-name').value = '';
  4474. document.getElementById('addrlist-modal-addr').value = '';
  4475. document.getElementById('addrlist-modal-comment').value = '';
  4476. document.getElementById('addrlist-modal-disabled').checked = false;
  4477. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  4478. if (submitBtn) submitBtn.innerText = 'Add to List';
  4479. document.getElementById('addrlist-modal').classList.remove('hidden');
  4480. }
  4481. function openEditAddrListModal(id) {
  4482. const e = (state.addressLists || []).find(item => item.id === id);
  4483. if (!e) return;
  4484. document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
  4485. document.getElementById('addrlist-modal-id').value = e.id;
  4486. document.getElementById('addrlist-modal-name').value = e.name;
  4487. document.getElementById('addrlist-modal-addr').value = e.address;
  4488. document.getElementById('addrlist-modal-comment').value = e.comment || '';
  4489. document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
  4490. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  4491. if (submitBtn) submitBtn.innerText = 'Save Changes';
  4492. document.getElementById('addrlist-modal').classList.remove('hidden');
  4493. }
  4494. function closeAddrListModal() {
  4495. document.getElementById('addrlist-modal').classList.add('hidden');
  4496. }
  4497. async function submitSaveAddrList(e) {
  4498. e.preventDefault();
  4499. const id = document.getElementById('addrlist-modal-id').value;
  4500. const name = document.getElementById('addrlist-modal-name').value.trim();
  4501. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  4502. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  4503. const disabled = document.getElementById('addrlist-modal-disabled').checked;
  4504. try {
  4505. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  4506. method: 'POST',
  4507. headers: { 'Content-Type': 'application/json' },
  4508. body: JSON.stringify({ id, name, address: addr, comment, disabled })
  4509. });
  4510. if (res.ok) {
  4511. showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
  4512. closeAddrListModal();
  4513. loadFirewall(false);
  4514. } else {
  4515. const err = await res.json();
  4516. showToast('Error', err.message || 'Failed to save address list', 'error');
  4517. }
  4518. } catch (err) {
  4519. showToast('Error', err.message, 'error');
  4520. }
  4521. }
  4522. async function toggleAddrListState(id, disabled) {
  4523. try {
  4524. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
  4525. method: 'POST',
  4526. headers: { 'Content-Type': 'application/json' },
  4527. body: JSON.stringify({ disabled })
  4528. });
  4529. if (res.ok) {
  4530. loadFirewall(false);
  4531. }
  4532. } catch (err) {
  4533. showToast('Error', err.message, 'error');
  4534. }
  4535. }
  4536. async function deleteAddrList(id) {
  4537. if (!confirm('Are you sure you want to delete this address list item?')) return;
  4538. try {
  4539. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4540. if (res.ok) {
  4541. showToast('Deleted', 'Address list item removed', 'info');
  4542. loadFirewall(false);
  4543. }
  4544. } catch (err) {
  4545. showToast('Error', err.message, 'error');
  4546. }
  4547. }
  4548. // ----------------- Geo-Location IP Management -----------------
  4549. async function loadGeoIP() {
  4550. try {
  4551. const [statusRes, countriesRes] = await Promise.all([
  4552. fetch(`${API_BASE}/firewall/geoip/status`),
  4553. fetch(`${API_BASE}/firewall/geoip/countries`)
  4554. ]);
  4555. if (statusRes.ok) state.geoStatus = await statusRes.json();
  4556. if (countriesRes.ok) state.geoCountries = await countriesRes.json();
  4557. updateGeoHeader();
  4558. renderGeoCountries();
  4559. } catch (err) {
  4560. console.error('Failed to load GeoIP:', err);
  4561. }
  4562. }
  4563. function getGeoUsageMap() {
  4564. const usage = {};
  4565. const checkRule = (r, type) => {
  4566. ['src_geoip', 'dst_geoip'].forEach(field => {
  4567. let val = (r && r[field]) || '';
  4568. let code = val.replace(/^!/, '').replace(/^geo:/, '').replace(/^geo_/, '').toUpperCase().trim();
  4569. if (code) {
  4570. if (!usage[code]) usage[code] = [];
  4571. const label = `${type} #${r.priority !== undefined ? r.priority : (r.id || '')}`;
  4572. if (!usage[code].includes(label)) usage[code].push(label);
  4573. }
  4574. });
  4575. };
  4576. (state.filterRules || []).forEach(r => checkRule(r, 'Filter'));
  4577. (state.natRules || []).forEach(r => checkRule(r, 'NAT'));
  4578. (state.mangleRules || []).forEach(r => checkRule(r, 'Mangle'));
  4579. return usage;
  4580. }
  4581. function updateGeoHeader() {
  4582. const s = state.geoStatus || {};
  4583. const statusBadge = document.getElementById('geo-status-badge');
  4584. if (statusBadge) {
  4585. statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
  4586. statusBadge.className = s.auto_update
  4587. ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
  4588. : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
  4589. }
  4590. const intervalLabel = document.getElementById('geo-interval-label');
  4591. if (intervalLabel) {
  4592. intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
  4593. }
  4594. const usageMap = getGeoUsageMap();
  4595. const inUseCount = Object.keys(usageMap).length;
  4596. const activeCountEl = document.getElementById('geo-stat-active-countries');
  4597. if (activeCountEl) activeCountEl.innerText = inUseCount.toLocaleString();
  4598. const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
  4599. if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
  4600. const lastSyncEl = document.getElementById('geo-stat-last-sync');
  4601. if (lastSyncEl) {
  4602. if (s.last_updated && !s.last_updated.startsWith('0001')) {
  4603. const d = new Date(s.last_updated);
  4604. lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  4605. } else {
  4606. lastSyncEl.innerText = 'Never (Sync Pending)';
  4607. }
  4608. }
  4609. const nextSyncEl = document.getElementById('geo-stat-next-sync');
  4610. if (nextSyncEl) {
  4611. if (s.next_update && !s.next_update.startsWith('0001')) {
  4612. const d = new Date(s.next_update);
  4613. nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  4614. } else {
  4615. nextSyncEl.innerText = '-';
  4616. }
  4617. }
  4618. const badge = document.getElementById('fw-badge-geo');
  4619. if (badge) badge.innerText = inUseCount || (state.geoCountries || []).filter(c => c.subnet_count > 0).length || 0;
  4620. }
  4621. function renderGeoCountries() {
  4622. const tbody = document.getElementById('geo-table-body');
  4623. const empty = document.getElementById('geo-empty');
  4624. if (!tbody) return;
  4625. tbody.innerHTML = '';
  4626. const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
  4627. const continent = document.getElementById('geo-continent-filter')?.value || '';
  4628. const inUseOnly = document.getElementById('geo-filter-inuse-only')?.checked;
  4629. const cachedOnly = document.getElementById('geo-filter-cached-only')?.checked;
  4630. const usageMap = getGeoUsageMap();
  4631. const countries = (state.geoCountries || []).filter(c => {
  4632. const isUsed = !!usageMap[c.code];
  4633. if (inUseOnly && !isUsed) return false;
  4634. if (cachedOnly && (!c.subnet_count || c.subnet_count === 0)) return false;
  4635. if (continent && c.continent !== continent) return false;
  4636. if (q) {
  4637. const matchCode = c.code.toLowerCase().includes(q);
  4638. const matchName = c.name.toLowerCase().includes(q);
  4639. if (!matchCode && !matchName) return false;
  4640. }
  4641. return true;
  4642. });
  4643. if (countries.length === 0) {
  4644. empty?.classList.remove('hidden');
  4645. return;
  4646. }
  4647. empty?.classList.add('hidden');
  4648. countries.forEach(c => {
  4649. const tr = document.createElement('tr');
  4650. const isUsed = !!usageMap[c.code];
  4651. const rulesUsing = usageMap[c.code] || [];
  4652. tr.className = `hover:bg-slate-800/40 transition text-xs ${isUsed ? 'bg-emerald-950/20' : ''}`;
  4653. let statusHtml = '';
  4654. if (isUsed) {
  4655. 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>`;
  4656. } else if (c.subnet_count > 0) {
  4657. 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>';
  4658. } else {
  4659. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-slate-500 bg-slate-800/60">READY</span>';
  4660. }
  4661. tr.innerHTML = `
  4662. <td class="py-2.5 px-3 text-center">
  4663. <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'}">
  4664. ${c.code}
  4665. </span>
  4666. </td>
  4667. <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
  4668. <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
  4669. <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
  4670. ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
  4671. </td>
  4672. <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
  4673. <td class="py-2.5 px-3">
  4674. ${statusHtml}
  4675. </td>
  4676. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  4677. <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>
  4678. <button onclick="viewGeoSubnets('${c.code}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
  4679. </td>
  4680. `;
  4681. tbody.appendChild(tr);
  4682. });
  4683. }
  4684. function quickFilterGeo(preset) {
  4685. const searchInput = document.getElementById('geo-search-input');
  4686. const continentSel = document.getElementById('geo-continent-filter');
  4687. const inUseCheck = document.getElementById('geo-filter-inuse-only');
  4688. const cachedCheck = document.getElementById('geo-filter-cached-only');
  4689. if (searchInput) searchInput.value = '';
  4690. if (continentSel) continentSel.value = '';
  4691. if (inUseCheck) inUseCheck.checked = false;
  4692. if (cachedCheck) cachedCheck.checked = false;
  4693. if (preset === 'GR') {
  4694. if (searchInput) searchInput.value = 'Greece';
  4695. } else if (preset === 'Europe') {
  4696. if (continentSel) continentSel.value = 'Europe';
  4697. } else if (preset === 'HIGHRISK') {
  4698. if (searchInput) searchInput.value = 'China';
  4699. }
  4700. renderGeoCountries();
  4701. }
  4702. async function toggleGeoCountry(code, enabled) {
  4703. try {
  4704. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
  4705. method: 'POST',
  4706. headers: { 'Content-Type': 'application/json' },
  4707. body: JSON.stringify({ enabled })
  4708. });
  4709. if (res.ok) {
  4710. showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
  4711. loadGeoIP();
  4712. } else {
  4713. const err = await res.json();
  4714. showToast('Error', err.message || 'Failed to toggle country', 'error');
  4715. }
  4716. } catch (err) {
  4717. showToast('Error', err.message, 'error');
  4718. }
  4719. }
  4720. async function updateGeoCountry(code) {
  4721. try {
  4722. showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
  4723. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
  4724. if (res.ok) {
  4725. const data = await res.json();
  4726. showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
  4727. loadGeoIP();
  4728. } else {
  4729. const err = await res.json();
  4730. showToast('Sync Error', err.message || 'Failed to sync country', 'error');
  4731. }
  4732. } catch (err) {
  4733. showToast('Error', err.message, 'error');
  4734. }
  4735. }
  4736. async function triggerGeoUpdateNow() {
  4737. const spinner = document.getElementById('geo-update-spinner');
  4738. if (spinner) spinner.classList.remove('hidden');
  4739. try {
  4740. const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
  4741. if (res.ok) {
  4742. showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
  4743. setTimeout(() => {
  4744. loadGeoIP();
  4745. if (spinner) spinner.classList.add('hidden');
  4746. }, 2500);
  4747. } else {
  4748. const err = await res.json();
  4749. showToast('Notice', err.message || 'Update in progress', 'info');
  4750. if (spinner) spinner.classList.add('hidden');
  4751. }
  4752. } catch (err) {
  4753. showToast('Error', err.message, 'error');
  4754. if (spinner) spinner.classList.add('hidden');
  4755. }
  4756. }
  4757. async function applyGeoPreset(preset) {
  4758. try {
  4759. const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
  4760. method: 'POST',
  4761. headers: { 'Content-Type': 'application/json' },
  4762. body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
  4763. });
  4764. if (res.ok) {
  4765. showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
  4766. loadGeoIP();
  4767. }
  4768. } catch (err) {
  4769. showToast('Error', err.message, 'error');
  4770. }
  4771. }
  4772. function openGeoIntervalModal() {
  4773. const s = state.geoStatus || {};
  4774. document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
  4775. const sel = document.getElementById('geo-cfg-interval');
  4776. const customBox = document.getElementById('geo-cfg-custom-box');
  4777. const customHoursInput = document.getElementById('geo-cfg-custom-hours');
  4778. const curHours = s.interval_hours || 24;
  4779. const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
  4780. if (matchOption) {
  4781. sel.value = String(curHours);
  4782. customBox.classList.add('hidden');
  4783. } else {
  4784. sel.value = 'custom';
  4785. customHoursInput.value = curHours;
  4786. customBox.classList.remove('hidden');
  4787. }
  4788. document.getElementById('geo-interval-modal').classList.remove('hidden');
  4789. }
  4790. function closeGeoIntervalModal() {
  4791. document.getElementById('geo-interval-modal').classList.add('hidden');
  4792. }
  4793. function toggleCustomGeoInterval() {
  4794. const val = document.getElementById('geo-cfg-interval').value;
  4795. const customBox = document.getElementById('geo-cfg-custom-box');
  4796. if (val === 'custom') {
  4797. customBox.classList.remove('hidden');
  4798. } else {
  4799. customBox.classList.add('hidden');
  4800. }
  4801. }
  4802. async function submitGeoIntervalSettings(e) {
  4803. e.preventDefault();
  4804. const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
  4805. const intervalVal = document.getElementById('geo-cfg-interval').value;
  4806. let hours = 24;
  4807. if (intervalVal === 'custom') {
  4808. hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
  4809. } else {
  4810. hours = parseInt(intervalVal, 10) || 24;
  4811. }
  4812. try {
  4813. const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
  4814. method: 'POST',
  4815. headers: { 'Content-Type': 'application/json' },
  4816. body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
  4817. });
  4818. if (res.ok) {
  4819. showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
  4820. closeGeoIntervalModal();
  4821. loadGeoIP();
  4822. } else {
  4823. const err = await res.json();
  4824. showToast('Error', err.message || 'Failed to save schedule', 'error');
  4825. }
  4826. } catch (err) {
  4827. showToast('Error', err.message, 'error');
  4828. }
  4829. }
  4830. async function viewGeoSubnets(code, name) {
  4831. if (!name) {
  4832. const found = (state.geoCountries || []).find(x => x.code === code);
  4833. name = found ? found.name : code;
  4834. }
  4835. document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
  4836. document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
  4837. const listEl = document.getElementById('geo-subnets-list');
  4838. listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
  4839. document.getElementById('geo-subnets-modal').classList.remove('hidden');
  4840. try {
  4841. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
  4842. if (res.ok) {
  4843. const data = await res.json();
  4844. const subnets = data.subnets || [];
  4845. if (subnets.length === 0) {
  4846. listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
  4847. } else {
  4848. listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
  4849. }
  4850. } else {
  4851. listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
  4852. }
  4853. } catch (err) {
  4854. listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
  4855. }
  4856. }
  4857. function closeGeoSubnetsModal() {
  4858. document.getElementById('geo-subnets-modal').classList.add('hidden');
  4859. }
  4860. // ----------------- Active Connections Tracking -----------------
  4861. async function loadConnections() {
  4862. try {
  4863. const res = await fetch(`${API_BASE}/firewall/connections`);
  4864. const data = await res.json();
  4865. state.connections = Array.isArray(data) ? data : [];
  4866. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  4867. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  4868. renderConnections();
  4869. } catch (err) {
  4870. console.error('Failed to load connections:', err);
  4871. }
  4872. }
  4873. function renderConnections() {
  4874. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  4875. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  4876. const tbody = document.getElementById('conns-table-body');
  4877. const empty = document.getElementById('conns-empty');
  4878. if (!tbody) return;
  4879. tbody.innerHTML = '';
  4880. const conns = (state.connections || []).filter(c => {
  4881. if (protoFilter && c.protocol !== protoFilter) return false;
  4882. if (search) {
  4883. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  4884. if (!line.includes(search)) return false;
  4885. }
  4886. return true;
  4887. });
  4888. if (conns.length === 0) {
  4889. empty?.classList.remove('hidden');
  4890. return;
  4891. }
  4892. empty?.classList.add('hidden');
  4893. conns.slice(0, 150).forEach(c => {
  4894. const tr = document.createElement('tr');
  4895. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  4896. let stateColor = 'text-slate-400';
  4897. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  4898. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  4899. tr.innerHTML = `
  4900. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  4901. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  4902. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  4903. <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>
  4904. <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>
  4905. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  4906. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  4907. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  4908. <td class="py-2.5 px-3 text-right font-sans">
  4909. <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>
  4910. </td>
  4911. `;
  4912. tbody.appendChild(tr);
  4913. });
  4914. }
  4915. async function killConnection(protocol, src, sport, dst, dport) {
  4916. try {
  4917. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  4918. method: 'POST',
  4919. headers: { 'Content-Type': 'application/json' },
  4920. body: JSON.stringify({ protocol, src, sport, dst, dport })
  4921. });
  4922. if (res.ok) {
  4923. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  4924. loadConnections();
  4925. }
  4926. } catch (err) {
  4927. showToast('Error', err.message, 'error');
  4928. }
  4929. }
  4930. async function resetFirewallCounters() {
  4931. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  4932. try {
  4933. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  4934. if (res.ok) {
  4935. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  4936. loadFirewall(false);
  4937. }
  4938. } catch (err) {
  4939. showToast('Error', err.message, 'error');
  4940. }
  4941. }
  4942. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  4943. function switchRoutesSubTab(tab) {
  4944. state.routesSubTab = tab;
  4945. const tabs = ['routes', 'rules', 'tables'];
  4946. tabs.forEach(t => {
  4947. const panel = document.getElementById(`routes-subtab-${t}`);
  4948. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  4949. if (panel) {
  4950. if (t === tab) panel.classList.remove('hidden');
  4951. else panel.classList.add('hidden');
  4952. }
  4953. if (btn) {
  4954. if (t === tab) {
  4955. 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';
  4956. } else {
  4957. 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';
  4958. }
  4959. }
  4960. });
  4961. }
  4962. async function loadRoutes() {
  4963. try {
  4964. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  4965. fetch(`${API_BASE}/routes`),
  4966. fetch(`${API_BASE}/routing/rules`),
  4967. fetch(`${API_BASE}/routing/tables`)
  4968. ]);
  4969. if (routesRes.ok) state.routes = await routesRes.json();
  4970. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  4971. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  4972. const bRoutes = document.getElementById('routes-badge-routes');
  4973. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  4974. const bRules = document.getElementById('routes-badge-rules');
  4975. if (bRules) bRules.innerText = (state.policyRules || []).length;
  4976. const bTables = document.getElementById('routes-badge-tables');
  4977. if (bTables) bTables.innerText = (state.routingTables || []).length;
  4978. const bRoutesCount = document.getElementById('badge-routes-count');
  4979. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  4980. renderRoutesList();
  4981. renderPolicyRules();
  4982. renderRoutingTables();
  4983. } catch (err) {
  4984. console.error('Failed to load routing:', err);
  4985. }
  4986. }
  4987. function renderRoutesList() {
  4988. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  4989. const tbody = document.getElementById('routes-table-body');
  4990. const empty = document.getElementById('routes-empty');
  4991. if (!tbody) return;
  4992. tbody.innerHTML = '';
  4993. // Update table filter select
  4994. const sel = document.getElementById('routes-filter-table');
  4995. if (sel) {
  4996. const cur = sel.value;
  4997. sel.innerHTML = '<option value="">All Tables</option>';
  4998. (state.routingTables || []).forEach(t => {
  4999. const opt = document.createElement('option');
  5000. opt.value = t.name;
  5001. opt.innerText = t.name;
  5002. if (t.name === cur) opt.selected = true;
  5003. sel.appendChild(opt);
  5004. });
  5005. }
  5006. const routes = (state.routes || []).filter(r => !tableFilter || r.routing_table === tableFilter);
  5007. document.getElementById('routes-count-badge').innerText = `${routes.length} Routes`;
  5008. if (routes.length === 0) {
  5009. empty?.classList.remove('hidden');
  5010. return;
  5011. }
  5012. empty?.classList.add('hidden');
  5013. routes.forEach(r => {
  5014. const tr = document.createElement('tr');
  5015. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  5016. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  5017. // MikroTik Flags string: D=Dynamic, A=Active, C=Connect, S=Static, X=Disabled
  5018. let flags = '';
  5019. if (r.dynamic) flags += 'D';
  5020. if (r.active) flags += 'A';
  5021. if (r.connect) flags += 'C';
  5022. if (r.static) flags += 'S';
  5023. if (r.disabled) flags += 'X';
  5024. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  5025. tr.innerHTML = `
  5026. <td class="py-2.5 px-3 text-center">
  5027. <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'}">
  5028. ${flags || '-'}
  5029. </span>
  5030. </td>
  5031. <td class="py-2.5 px-3 font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${r.dst_address}</td>
  5032. <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>
  5033. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  5034. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  5035. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  5036. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  5037. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5038. ${r.static ? `
  5039. <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>
  5040. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  5041. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5042. ` : `
  5043. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  5044. `}
  5045. </td>
  5046. `;
  5047. tbody.appendChild(tr);
  5048. });
  5049. }
  5050. function openAddRouteModal() {
  5051. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  5052. document.getElementById('route-modal-id').value = '';
  5053. document.getElementById('route-modal-old-dst').value = '';
  5054. document.getElementById('route-modal-old-gw').value = '';
  5055. document.getElementById('route-modal-old-distance').value = '';
  5056. document.getElementById('route-modal-old-table').value = '';
  5057. document.getElementById('route-modal-old-iface').value = '';
  5058. const dstInput = document.getElementById('route-modal-dst');
  5059. const gwInput = document.getElementById('route-modal-gw');
  5060. const distInput = document.getElementById('route-modal-distance');
  5061. const ifaceSelect = document.getElementById('route-modal-iface');
  5062. const tableSelect = document.getElementById('route-modal-table');
  5063. const commentInput = document.getElementById('route-modal-comment');
  5064. const disCheck = document.getElementById('route-modal-disabled');
  5065. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  5066. dstInput.disabled = false;
  5067. dstInput.value = '0.0.0.0/0';
  5068. gwInput.disabled = false;
  5069. gwInput.value = '';
  5070. distInput.disabled = false;
  5071. distInput.value = '1';
  5072. ifaceSelect.disabled = false;
  5073. tableSelect.disabled = false;
  5074. commentInput.disabled = false;
  5075. commentInput.value = '';
  5076. disCheck.disabled = false;
  5077. disCheck.checked = false;
  5078. if (saveBtn) saveBtn.classList.remove('hidden');
  5079. populateInterfaceSelect('route-modal-iface');
  5080. // Populate tables
  5081. tableSelect.innerHTML = '';
  5082. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  5083. const opt = document.createElement('option');
  5084. opt.value = t.name;
  5085. opt.innerText = t.name;
  5086. if (t.name === 'main') opt.selected = true;
  5087. tableSelect.appendChild(opt);
  5088. });
  5089. document.getElementById('route-modal').classList.remove('hidden');
  5090. }
  5091. function openEditRouteModal(id) {
  5092. const r = (state.routes || []).find(route => route.id === id);
  5093. if (!r) return;
  5094. const isStatic = !!r.static;
  5095. document.getElementById('route-modal-title').innerText = isStatic
  5096. ? `Edit Route: ${r.dst_address}`
  5097. : `Route Properties (Read Only): ${r.dst_address}`;
  5098. document.getElementById('route-modal-id').value = r.id;
  5099. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  5100. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  5101. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  5102. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  5103. document.getElementById('route-modal-old-iface').value = r.interface || '';
  5104. const dstInput = document.getElementById('route-modal-dst');
  5105. const gwInput = document.getElementById('route-modal-gw');
  5106. const distInput = document.getElementById('route-modal-distance');
  5107. const ifaceSelect = document.getElementById('route-modal-iface');
  5108. const tableSelect = document.getElementById('route-modal-table');
  5109. const commentInput = document.getElementById('route-modal-comment');
  5110. const disCheck = document.getElementById('route-modal-disabled');
  5111. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  5112. dstInput.value = r.dst_address;
  5113. gwInput.value = r.gateway || '';
  5114. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  5115. commentInput.value = r.comment || '';
  5116. disCheck.checked = !!r.disabled;
  5117. dstInput.disabled = !isStatic;
  5118. gwInput.disabled = !isStatic;
  5119. distInput.disabled = !isStatic;
  5120. ifaceSelect.disabled = !isStatic;
  5121. tableSelect.disabled = !isStatic;
  5122. commentInput.disabled = !isStatic;
  5123. disCheck.disabled = !isStatic;
  5124. if (saveBtn) {
  5125. if (isStatic) {
  5126. saveBtn.classList.remove('hidden');
  5127. } else {
  5128. saveBtn.classList.add('hidden');
  5129. }
  5130. }
  5131. populateInterfaceSelect('route-modal-iface', r.interface);
  5132. tableSelect.innerHTML = '';
  5133. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  5134. const opt = document.createElement('option');
  5135. opt.value = t.name;
  5136. opt.innerText = t.name;
  5137. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  5138. tableSelect.appendChild(opt);
  5139. });
  5140. document.getElementById('route-modal').classList.remove('hidden');
  5141. }
  5142. function closeRouteModal() {
  5143. document.getElementById('route-modal').classList.add('hidden');
  5144. }
  5145. async function submitSaveRoute(e) {
  5146. e.preventDefault();
  5147. const id = document.getElementById('route-modal-id').value;
  5148. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  5149. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  5150. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  5151. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  5152. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  5153. const dst = document.getElementById('route-modal-dst').value.trim();
  5154. const gw = document.getElementById('route-modal-gw').value.trim();
  5155. const table = document.getElementById('route-modal-table').value;
  5156. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  5157. const iface = document.getElementById('route-modal-iface').value;
  5158. const comment = document.getElementById('route-modal-comment').value.trim();
  5159. const disabled = document.getElementById('route-modal-disabled').checked;
  5160. if (!dst) {
  5161. showToast('Error', 'Destination address is required', 'error');
  5162. return;
  5163. }
  5164. if (!gw && !iface) {
  5165. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  5166. return;
  5167. }
  5168. const payload = {
  5169. id,
  5170. old_dst_address: oldDst,
  5171. old_gateway: oldGw,
  5172. old_routing_table: oldTable,
  5173. old_interface: oldIface,
  5174. dst_address: dst,
  5175. gateway: gw || iface,
  5176. routing_table: table,
  5177. distance,
  5178. interface: iface,
  5179. comment,
  5180. disabled
  5181. };
  5182. if (oldDistStr !== undefined && oldDistStr !== '') {
  5183. payload.old_distance = parseInt(oldDistStr, 10);
  5184. }
  5185. try {
  5186. const res = await fetch(`${API_BASE}/routes`, {
  5187. method: 'POST',
  5188. headers: { 'Content-Type': 'application/json' },
  5189. body: JSON.stringify(payload)
  5190. });
  5191. if (res.ok) {
  5192. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  5193. closeRouteModal();
  5194. loadRoutes();
  5195. } else {
  5196. const err = await res.json();
  5197. showToast('Error', err.message || 'Failed to save route', 'error');
  5198. }
  5199. } catch (err) {
  5200. showToast('Error', err.message, 'error');
  5201. }
  5202. }
  5203. async function toggleRouteState(id, disabled) {
  5204. try {
  5205. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  5206. method: 'POST',
  5207. headers: { 'Content-Type': 'application/json' },
  5208. body: JSON.stringify({ disabled })
  5209. });
  5210. if (res.ok) loadRoutes();
  5211. } catch (err) {
  5212. showToast('Error', err.message, 'error');
  5213. }
  5214. }
  5215. async function deleteRoute(id) {
  5216. if (!confirm('Are you sure you want to delete this route?')) return;
  5217. try {
  5218. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5219. if (res.ok) {
  5220. showToast('Deleted', 'Route removed', 'success');
  5221. loadRoutes();
  5222. }
  5223. } catch (err) {
  5224. showToast('Error', err.message, 'error');
  5225. }
  5226. }
  5227. // ----------------- Policy Rules (/ip route rule) -----------------
  5228. function renderPolicyRules() {
  5229. const tbody = document.getElementById('rules-table-body');
  5230. const empty = document.getElementById('rules-empty');
  5231. if (!tbody) return;
  5232. tbody.innerHTML = '';
  5233. const rules = state.policyRules || [];
  5234. document.getElementById('rules-count-badge').innerText = `${rules.length} Rules`;
  5235. if (rules.length === 0) {
  5236. empty?.classList.remove('hidden');
  5237. return;
  5238. }
  5239. empty?.classList.add('hidden');
  5240. rules.forEach(pr => {
  5241. const tr = document.createElement('tr');
  5242. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  5243. tr.innerHTML = `
  5244. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  5245. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  5246. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  5247. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  5248. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  5249. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  5250. <td class="py-2.5 px-3 text-right font-sans">
  5251. ${pr.priority < 32766 && pr.priority > 0 ? `
  5252. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5253. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  5254. </td>
  5255. `;
  5256. tbody.appendChild(tr);
  5257. });
  5258. }
  5259. function openAddPolicyRuleModal() {
  5260. document.getElementById('prule-modal-pref').value = (state.policyRules || []).length * 10 + 1000;
  5261. document.getElementById('prule-modal-mark').value = '';
  5262. document.getElementById('prule-modal-src').value = '';
  5263. document.getElementById('prule-modal-dst').value = '';
  5264. const sel = document.getElementById('prule-modal-table');
  5265. sel.innerHTML = '';
  5266. (state.routingTables || []).forEach(t => {
  5267. const opt = document.createElement('option');
  5268. opt.value = t.name;
  5269. opt.innerText = t.name;
  5270. sel.appendChild(opt);
  5271. });
  5272. document.getElementById('prule-modal').classList.remove('hidden');
  5273. }
  5274. function closePolicyRuleModal() {
  5275. document.getElementById('prule-modal').classList.add('hidden');
  5276. }
  5277. async function submitSavePolicyRule(e) {
  5278. e.preventDefault();
  5279. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  5280. const mark = document.getElementById('prule-modal-mark').value.trim();
  5281. const src = document.getElementById('prule-modal-src').value.trim();
  5282. const dst = document.getElementById('prule-modal-dst').value.trim();
  5283. const table = document.getElementById('prule-modal-table').value;
  5284. const action = document.getElementById('prule-modal-action').value;
  5285. try {
  5286. const res = await fetch(`${API_BASE}/routing/rules`, {
  5287. method: 'POST',
  5288. headers: { 'Content-Type': 'application/json' },
  5289. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  5290. });
  5291. if (res.ok) {
  5292. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  5293. closePolicyRuleModal();
  5294. loadRoutes();
  5295. } else {
  5296. const err = await res.json();
  5297. showToast('Error', err.message, 'error');
  5298. }
  5299. } catch (err) {
  5300. showToast('Error', err.message, 'error');
  5301. }
  5302. }
  5303. async function deletePolicyRule(id) {
  5304. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  5305. try {
  5306. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5307. if (res.ok) {
  5308. showToast('Rule Removed', 'Policy rule deleted', 'success');
  5309. loadRoutes();
  5310. }
  5311. } catch (err) {
  5312. showToast('Error', err.message, 'error');
  5313. }
  5314. }
  5315. // ----------------- Routing Tables -----------------
  5316. function renderRoutingTables() {
  5317. const tbody = document.getElementById('tables-table-body');
  5318. if (!tbody) return;
  5319. tbody.innerHTML = '';
  5320. (state.routingTables || []).forEach(t => {
  5321. const tr = document.createElement('tr');
  5322. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  5323. tr.innerHTML = `
  5324. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  5325. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  5326. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  5327. `;
  5328. tbody.appendChild(tr);
  5329. });
  5330. }
  5331. function openAddTableModal() {
  5332. document.getElementById('table-modal-name').value = '';
  5333. document.getElementById('table-modal-id').value = '';
  5334. document.getElementById('table-modal-comment').value = '';
  5335. document.getElementById('table-modal').classList.remove('hidden');
  5336. }
  5337. function closeTableModal() {
  5338. document.getElementById('table-modal').classList.add('hidden');
  5339. }
  5340. async function submitSaveTable(e) {
  5341. e.preventDefault();
  5342. const name = document.getElementById('table-modal-name').value.trim();
  5343. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  5344. const comment = document.getElementById('table-modal-comment').value.trim();
  5345. try {
  5346. const res = await fetch(`${API_BASE}/routing/tables`, {
  5347. method: 'POST',
  5348. headers: { 'Content-Type': 'application/json' },
  5349. body: JSON.stringify({ name, table_id: id, comment })
  5350. });
  5351. if (res.ok) {
  5352. showToast('Table Created', `Routing table ${name} registered`, 'success');
  5353. closeTableModal();
  5354. loadRoutes();
  5355. } else {
  5356. const err = await res.json();
  5357. showToast('Error', err.message, 'error');
  5358. }
  5359. } catch (err) {
  5360. showToast('Error', err.message, 'error');
  5361. }
  5362. }
  5363. async function loadDebianConfig() {
  5364. const view = document.getElementById('debian-config-view');
  5365. view.innerText = 'Generating live configuration...';
  5366. try {
  5367. const res = await fetch(`${API_BASE}/debian/config`);
  5368. const data = await res.json();
  5369. view.innerText = data.content || '# Empty config';
  5370. } catch (err) {
  5371. view.innerText = 'Failed to generate Debian network config.';
  5372. }
  5373. }
  5374. async function saveDebianConfig() {
  5375. try {
  5376. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  5377. const data = await res.json();
  5378. if (res.ok) {
  5379. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  5380. loadDebianConfig();
  5381. }
  5382. } catch (err) {
  5383. showToast('Error', err.message, 'error');
  5384. }
  5385. }
  5386. function showToast(title, message, type = 'info') {
  5387. const container = document.getElementById('toast-container');
  5388. const toast = document.createElement('div');
  5389. const borderColors = {
  5390. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  5391. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  5392. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  5393. };
  5394. 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}`;
  5395. toast.innerHTML = `
  5396. <div class="flex-1">
  5397. <div class="font-bold text-xs text-white">${title}</div>
  5398. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${message}</div>
  5399. </div>
  5400. `;
  5401. container.appendChild(toast);
  5402. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  5403. setTimeout(() => {
  5404. toast.classList.add('opacity-0', 'translate-y-2');
  5405. setTimeout(() => toast.remove(), 300);
  5406. }, 4000);
  5407. }
  5408. function formatTraffic(bytesPerSec) {
  5409. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  5410. const kb = bytesPerSec / 1024;
  5411. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  5412. const mb = kb / 1024;
  5413. return `${mb.toFixed(2)} MB/s`;
  5414. }
  5415. function toggleSidebar() {
  5416. const sb = document.getElementById('sidebar');
  5417. sb.classList.toggle('-translate-x-full');
  5418. }
  5419. // ======================== EoIP (Ethernet over IP) ========================
  5420. async function loadEoIP(populate = true) {
  5421. try {
  5422. const res = await fetch(`${API_BASE}/vpn/eoip`);
  5423. const data = await res.json();
  5424. state.eoipTunnels = Array.isArray(data) ? data : [];
  5425. const badge = document.getElementById('eoip-count-badge');
  5426. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  5427. const sideBadge = document.getElementById('badge-eoip-count');
  5428. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  5429. renderEoIPTunnels();
  5430. } catch (err) {
  5431. console.error('Failed to load EoIP:', err);
  5432. }
  5433. }
  5434. function renderEoIPTunnels() {
  5435. const tbody = document.getElementById('eoip-table-body');
  5436. const empty = document.getElementById('eoip-empty');
  5437. if (!tbody) return;
  5438. tbody.innerHTML = '';
  5439. const tunnels = state.eoipTunnels || [];
  5440. if (tunnels.length === 0) {
  5441. empty?.classList.remove('hidden');
  5442. return;
  5443. }
  5444. empty?.classList.add('hidden');
  5445. tunnels.forEach(t => {
  5446. const tr = document.createElement('tr');
  5447. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  5448. tr.innerHTML = `
  5449. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  5450. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  5451. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  5452. <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>
  5453. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  5454. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  5455. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  5456. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  5457. <td class="py-2.5 px-3 font-mono text-[11px]">
  5458. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  5459. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  5460. </td>
  5461. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  5462. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  5463. <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>
  5464. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  5465. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  5466. </td>
  5467. `;
  5468. tbody.appendChild(tr);
  5469. });
  5470. }
  5471. function openAddEoIPModal() {
  5472. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  5473. document.getElementById('eoip-modal-id').value = '';
  5474. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  5475. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  5476. document.getElementById('eoip-modal-remote').value = '';
  5477. document.getElementById('eoip-modal-ip').value = '';
  5478. document.getElementById('eoip-modal-local').value = '';
  5479. document.getElementById('eoip-modal-mac').value = '';
  5480. document.getElementById('eoip-modal-mtu').value = '1500';
  5481. document.getElementById('eoip-modal-comment').value = '';
  5482. document.getElementById('eoip-modal-clampmss').checked = true;
  5483. document.getElementById('eoip-modal-disabled').checked = false;
  5484. document.getElementById('eoip-modal').classList.remove('hidden');
  5485. }
  5486. function openEditEoIPModal(id) {
  5487. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  5488. if (!t) return;
  5489. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  5490. document.getElementById('eoip-modal-id').value = t.id;
  5491. document.getElementById('eoip-modal-name').value = t.name;
  5492. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  5493. document.getElementById('eoip-modal-remote').value = t.remote_address;
  5494. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  5495. document.getElementById('eoip-modal-local').value = t.local_address || '';
  5496. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  5497. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  5498. document.getElementById('eoip-modal-comment').value = t.comment || '';
  5499. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  5500. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  5501. document.getElementById('eoip-modal').classList.remove('hidden');
  5502. }
  5503. function closeEoIPModal() {
  5504. document.getElementById('eoip-modal').classList.add('hidden');
  5505. }
  5506. async function submitSaveEoIP(e) {
  5507. e.preventDefault();
  5508. const id = document.getElementById('eoip-modal-id').value;
  5509. const name = document.getElementById('eoip-modal-name').value.trim();
  5510. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  5511. const remote = document.getElementById('eoip-modal-remote').value.trim();
  5512. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  5513. const local = document.getElementById('eoip-modal-local').value.trim();
  5514. const mac = document.getElementById('eoip-modal-mac').value.trim();
  5515. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  5516. const comment = document.getElementById('eoip-modal-comment').value.trim();
  5517. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  5518. const disabled = document.getElementById('eoip-modal-disabled').checked;
  5519. try {
  5520. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  5521. method: 'POST',
  5522. headers: { 'Content-Type': 'application/json' },
  5523. body: JSON.stringify({
  5524. id,
  5525. name,
  5526. tunnel_id: tunnelId,
  5527. remote_address: remote,
  5528. ip_address: ipAddress,
  5529. local_address: local,
  5530. mac_address: mac,
  5531. mtu,
  5532. clamp_mss: clampMss,
  5533. comment,
  5534. disabled
  5535. })
  5536. });
  5537. if (res.ok) {
  5538. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  5539. closeEoIPModal();
  5540. loadEoIP(false);
  5541. fetchData(false);
  5542. } else {
  5543. const err = await res.json();
  5544. showToast('Error', err.message, 'error');
  5545. }
  5546. } catch (err) {
  5547. showToast('Error', err.message, 'error');
  5548. }
  5549. }
  5550. async function toggleEoIPState(id, disabled) {
  5551. try {
  5552. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  5553. method: 'POST',
  5554. headers: { 'Content-Type': 'application/json' },
  5555. body: JSON.stringify({ disabled })
  5556. });
  5557. if (res.ok) {
  5558. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  5559. loadEoIP(false);
  5560. fetchData(false);
  5561. }
  5562. } catch (err) {
  5563. showToast('Error', err.message, 'error');
  5564. }
  5565. }
  5566. async function deleteEoIP(id) {
  5567. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  5568. try {
  5569. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5570. if (res.ok) {
  5571. showToast('Deleted', 'EoIP tunnel removed', 'success');
  5572. loadEoIP(false);
  5573. fetchData(false);
  5574. }
  5575. } catch (err) {
  5576. showToast('Error', err.message, 'error');
  5577. }
  5578. }
  5579. // ======================== PPP Central Hub & Servers ========================
  5580. function switchPPPSubTab(tab) {
  5581. state.pppSubTab = tab;
  5582. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  5583. tabs.forEach(t => {
  5584. const panel = document.getElementById(`ppp-subtab-${t}`);
  5585. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  5586. if (panel) {
  5587. if (t === tab) panel.classList.remove('hidden');
  5588. else panel.classList.add('hidden');
  5589. }
  5590. if (btn) {
  5591. if (t === tab) {
  5592. 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';
  5593. } else {
  5594. 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';
  5595. }
  5596. }
  5597. });
  5598. const addBtn = document.getElementById('ppp-primary-add-btn');
  5599. if (addBtn) {
  5600. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  5601. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  5602. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  5603. else addBtn.innerHTML = '<span>Save Config</span>';
  5604. }
  5605. if (tab === 'active') loadPPPSessions();
  5606. }
  5607. function openCurrentPPPModal() {
  5608. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  5609. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  5610. else if (state.pppSubTab === 'active') loadPPPSessions();
  5611. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  5612. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  5613. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  5614. }
  5615. async function loadPPP(populateDropdowns = true) {
  5616. await Promise.all([
  5617. loadPPPSecrets(),
  5618. loadPPPProfiles(),
  5619. loadPPPServers(),
  5620. loadPPPSessions()
  5621. ]);
  5622. }
  5623. async function loadPPPSecrets() {
  5624. try {
  5625. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  5626. const data = await res.json();
  5627. state.pppSecrets = Array.isArray(data) ? data : [];
  5628. const b = document.getElementById('ppp-badge-secrets');
  5629. if (b) b.innerText = state.pppSecrets.length;
  5630. const b2 = document.getElementById('secrets-count-badge');
  5631. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  5632. renderPPPSecrets();
  5633. } catch (err) {
  5634. console.error('Failed to load PPP secrets:', err);
  5635. }
  5636. }
  5637. function renderPPPSecrets() {
  5638. const tbody = document.getElementById('secrets-table-body');
  5639. const empty = document.getElementById('secrets-empty');
  5640. if (!tbody) return;
  5641. tbody.innerHTML = '';
  5642. const secrets = state.pppSecrets || [];
  5643. if (secrets.length === 0) {
  5644. empty?.classList.remove('hidden');
  5645. return;
  5646. }
  5647. empty?.classList.add('hidden');
  5648. secrets.forEach(s => {
  5649. const tr = document.createElement('tr');
  5650. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  5651. tr.innerHTML = `
  5652. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  5653. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  5654. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  5655. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  5656. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  5657. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  5658. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  5659. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  5660. <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>
  5661. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  5662. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  5663. </td>
  5664. `;
  5665. tbody.appendChild(tr);
  5666. });
  5667. }
  5668. async function loadPPPProfiles() {
  5669. try {
  5670. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  5671. const data = await res.json();
  5672. state.pppProfiles = Array.isArray(data) ? data : [];
  5673. const b = document.getElementById('ppp-badge-profiles');
  5674. if (b) b.innerText = state.pppProfiles.length;
  5675. const b2 = document.getElementById('profiles-count-badge');
  5676. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  5677. // Populate profile selects across modals
  5678. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  5679. selects.forEach(sid => {
  5680. const el = document.getElementById(sid);
  5681. if (!el) return;
  5682. const cur = el.value;
  5683. el.innerHTML = '';
  5684. state.pppProfiles.forEach(p => {
  5685. const opt = document.createElement('option');
  5686. opt.value = p.name;
  5687. opt.innerText = `${p.name} (${p.remote_address})`;
  5688. if (p.name === cur) opt.selected = true;
  5689. el.appendChild(opt);
  5690. });
  5691. });
  5692. renderPPPProfiles();
  5693. } catch (err) {
  5694. console.error('Failed to load PPP profiles:', err);
  5695. }
  5696. }
  5697. function renderPPPProfiles() {
  5698. const tbody = document.getElementById('profiles-table-body');
  5699. if (!tbody) return;
  5700. tbody.innerHTML = '';
  5701. (state.pppProfiles || []).forEach(p => {
  5702. const isDefault = p.name.startsWith('default');
  5703. const tr = document.createElement('tr');
  5704. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  5705. tr.innerHTML = `
  5706. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  5707. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  5708. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  5709. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  5710. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  5711. <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>
  5712. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  5713. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  5714. ${!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>`}
  5715. </td>
  5716. `;
  5717. tbody.appendChild(tr);
  5718. });
  5719. }
  5720. async function loadPPPServers() {
  5721. try {
  5722. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  5723. fetch(`${API_BASE}/vpn/servers/pppoe`),
  5724. fetch(`${API_BASE}/vpn/servers/pptp`),
  5725. fetch(`${API_BASE}/vpn/servers/l2tp`),
  5726. fetch(`${API_BASE}/vpn/servers/ipsec`)
  5727. ]);
  5728. if (pppoeRes.ok) {
  5729. state.pppoeServer = await pppoeRes.json();
  5730. const s = state.pppoeServer;
  5731. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  5732. document.getElementById('pppoe-server-name').value = s.service_name || 'proxmox-pppoe';
  5733. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  5734. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  5735. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  5736. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  5737. const pill = document.getElementById('pppoe-server-status-pill');
  5738. if (pill) {
  5739. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  5740. 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';
  5741. }
  5742. setDotBadge('ppp-badge-pppoe-state', s.running);
  5743. }
  5744. if (pptpRes.ok) {
  5745. state.pptpServer = await pptpRes.json();
  5746. const s = state.pptpServer;
  5747. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  5748. document.getElementById('pptp-server-port').value = s.port || 1723;
  5749. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  5750. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  5751. const pill = document.getElementById('pptp-server-status-pill');
  5752. if (pill) {
  5753. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  5754. 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';
  5755. }
  5756. setDotBadge('ppp-badge-pptp-state', s.running);
  5757. }
  5758. if (l2tpRes.ok) {
  5759. state.l2tpServer = await l2tpRes.json();
  5760. const s = state.l2tpServer;
  5761. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  5762. document.getElementById('l2tp-server-port').value = s.port || 1701;
  5763. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  5764. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  5765. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  5766. const pill = document.getElementById('l2tp-server-status-pill');
  5767. if (pill) {
  5768. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  5769. 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';
  5770. }
  5771. setDotBadge('ppp-badge-l2tp-state', s.running);
  5772. }
  5773. if (ipsecRes.ok) {
  5774. state.ipsecServer = await ipsecRes.json();
  5775. const s = state.ipsecServer;
  5776. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  5777. if (modalEn) modalEn.checked = !!s.enabled;
  5778. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  5779. if (modalPsk) modalPsk.value = s.preshared_key || '';
  5780. const modalPool = document.getElementById('modal-ipsec-server-pool');
  5781. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  5782. const modalDns = document.getElementById('modal-ipsec-server-dns');
  5783. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  5784. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  5785. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  5786. const pill = document.getElementById('modal-ipsec-server-status');
  5787. if (pill) {
  5788. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  5789. 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';
  5790. }
  5791. }
  5792. } catch (err) {
  5793. console.error('Failed to load VPN servers:', err);
  5794. }
  5795. }
  5796. async function loadPPPSessions() {
  5797. try {
  5798. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  5799. const data = await res.json();
  5800. state.pppActiveSessions = Array.isArray(data) ? data : [];
  5801. const b = document.getElementById('ppp-badge-active');
  5802. if (b) b.innerText = state.pppActiveSessions.length;
  5803. const sideB = document.getElementById('badge-ppp-sessions');
  5804. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  5805. renderPPPSessions();
  5806. } catch (err) {
  5807. console.error('Failed to load active PPP sessions:', err);
  5808. }
  5809. }
  5810. function renderPPPSessions() {
  5811. const tbody = document.getElementById('active-ppp-table-body');
  5812. const empty = document.getElementById('active-ppp-empty');
  5813. if (!tbody) return;
  5814. tbody.innerHTML = '';
  5815. const list = state.pppActiveSessions || [];
  5816. if (list.length === 0) {
  5817. empty?.classList.remove('hidden');
  5818. return;
  5819. }
  5820. empty?.classList.add('hidden');
  5821. list.forEach(s => {
  5822. const tr = document.createElement('tr');
  5823. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  5824. tr.innerHTML = `
  5825. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  5826. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  5827. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  5828. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  5829. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  5830. <td class="py-2.5 px-3 text-[11px]">
  5831. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  5832. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  5833. </td>
  5834. <td class="py-2.5 px-3 text-right font-sans">
  5835. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  5836. </td>
  5837. `;
  5838. tbody.appendChild(tr);
  5839. });
  5840. }
  5841. async function disconnectPPPSession(iface) {
  5842. if (!confirm(`Disconnect session ${iface}?`)) return;
  5843. try {
  5844. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  5845. if (res.ok) {
  5846. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  5847. loadPPPSessions();
  5848. }
  5849. } catch (err) {
  5850. showToast('Error', err.message, 'error');
  5851. }
  5852. }
  5853. // PPP Secret Modal handlers
  5854. function openAddPPPSecretModal() {
  5855. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  5856. document.getElementById('secret-modal-id').value = '';
  5857. document.getElementById('secret-modal-name').value = '';
  5858. document.getElementById('secret-modal-password').value = '';
  5859. document.getElementById('secret-modal-service').value = 'any';
  5860. document.getElementById('secret-modal-profile').value = 'default';
  5861. document.getElementById('secret-modal-local').value = '';
  5862. document.getElementById('secret-modal-remote').value = '';
  5863. document.getElementById('secret-modal-comment').value = '';
  5864. document.getElementById('secret-modal-disabled').checked = false;
  5865. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  5866. }
  5867. function openEditPPPSecretModal(id) {
  5868. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  5869. if (!s) return;
  5870. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  5871. document.getElementById('secret-modal-id').value = s.id;
  5872. document.getElementById('secret-modal-name').value = s.name;
  5873. document.getElementById('secret-modal-password').value = s.password;
  5874. document.getElementById('secret-modal-service').value = s.service || 'any';
  5875. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  5876. document.getElementById('secret-modal-local').value = s.local_address || '';
  5877. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  5878. document.getElementById('secret-modal-comment').value = s.comment || '';
  5879. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  5880. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  5881. }
  5882. function closePPPSecretModal() {
  5883. document.getElementById('ppp-secret-modal').classList.add('hidden');
  5884. }
  5885. async function submitSavePPPSecret(e) {
  5886. e.preventDefault();
  5887. const id = document.getElementById('secret-modal-id').value;
  5888. const name = document.getElementById('secret-modal-name').value.trim();
  5889. const password = document.getElementById('secret-modal-password').value.trim();
  5890. const service = document.getElementById('secret-modal-service').value;
  5891. const profile = document.getElementById('secret-modal-profile').value;
  5892. const local = document.getElementById('secret-modal-local').value.trim();
  5893. const remote = document.getElementById('secret-modal-remote').value.trim();
  5894. const comment = document.getElementById('secret-modal-comment').value.trim();
  5895. const disabled = document.getElementById('secret-modal-disabled').checked;
  5896. try {
  5897. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  5898. method: 'POST',
  5899. headers: { 'Content-Type': 'application/json' },
  5900. body: JSON.stringify({
  5901. id,
  5902. name,
  5903. password,
  5904. service,
  5905. profile,
  5906. local_address: local,
  5907. remote_address: remote,
  5908. comment,
  5909. disabled
  5910. })
  5911. });
  5912. if (res.ok) {
  5913. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  5914. closePPPSecretModal();
  5915. loadPPPSecrets();
  5916. } else {
  5917. const err = await res.json();
  5918. showToast('Error', err.message, 'error');
  5919. }
  5920. } catch (err) {
  5921. showToast('Error', err.message, 'error');
  5922. }
  5923. }
  5924. async function togglePPPSecretState(id, disabled) {
  5925. try {
  5926. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  5927. method: 'POST',
  5928. headers: { 'Content-Type': 'application/json' },
  5929. body: JSON.stringify({ disabled })
  5930. });
  5931. if (res.ok) {
  5932. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  5933. loadPPPSecrets();
  5934. }
  5935. } catch (err) {
  5936. showToast('Error', err.message, 'error');
  5937. }
  5938. }
  5939. async function deletePPPSecret(id) {
  5940. if (!confirm('Are you sure you want to delete this secret account?')) return;
  5941. try {
  5942. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5943. if (res.ok) {
  5944. showToast('Deleted', 'Secret account removed', 'success');
  5945. loadPPPSecrets();
  5946. }
  5947. } catch (err) {
  5948. showToast('Error', err.message, 'error');
  5949. }
  5950. }
  5951. // PPP Profile Modal handlers
  5952. function openAddPPPProfileModal() {
  5953. document.getElementById('profile-modal-name').value = '';
  5954. document.getElementById('profile-modal-local').value = '10.10.10.1';
  5955. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  5956. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  5957. document.getElementById('profile-modal-encryption').value = 'required';
  5958. document.getElementById('profile-modal-onlyone').checked = true;
  5959. document.getElementById('profile-modal-comment').value = '';
  5960. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  5961. }
  5962. function closePPPProfileModal() {
  5963. document.getElementById('ppp-profile-modal').classList.add('hidden');
  5964. }
  5965. async function submitSavePPPProfile(e) {
  5966. e.preventDefault();
  5967. const name = document.getElementById('profile-modal-name').value.trim();
  5968. const local = document.getElementById('profile-modal-local').value.trim();
  5969. const remote = document.getElementById('profile-modal-remote').value.trim();
  5970. const dns = document.getElementById('profile-modal-dns').value.trim();
  5971. const enc = document.getElementById('profile-modal-encryption').value;
  5972. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  5973. const comment = document.getElementById('profile-modal-comment').value.trim();
  5974. try {
  5975. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  5976. method: 'POST',
  5977. headers: { 'Content-Type': 'application/json' },
  5978. body: JSON.stringify({
  5979. id: name,
  5980. name,
  5981. local_address: local,
  5982. remote_address: remote,
  5983. dns_servers: dns,
  5984. use_encryption: enc,
  5985. only_one: onlyone,
  5986. comment
  5987. })
  5988. });
  5989. if (res.ok) {
  5990. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  5991. closePPPProfileModal();
  5992. loadPPPProfiles();
  5993. } else {
  5994. const err = await res.json();
  5995. showToast('Error', err.message, 'error');
  5996. }
  5997. } catch (err) {
  5998. showToast('Error', err.message, 'error');
  5999. }
  6000. }
  6001. async function deletePPPProfile(name) {
  6002. if (!confirm(`Delete PPP profile ${name}?`)) return;
  6003. try {
  6004. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  6005. if (res.ok) {
  6006. showToast('Deleted', 'Profile removed', 'success');
  6007. loadPPPProfiles();
  6008. } else {
  6009. const err = await res.json();
  6010. showToast('Error', err.message, 'error');
  6011. }
  6012. } catch (err) {
  6013. showToast('Error', err.message, 'error');
  6014. }
  6015. }
  6016. // Server Config submissions
  6017. async function savePPPoEServerConfig(e) {
  6018. e.preventDefault();
  6019. const enabled = document.getElementById('pppoe-server-enabled').checked;
  6020. const name = document.getElementById('pppoe-server-name').value.trim();
  6021. const iface = document.getElementById('pppoe-server-iface').value;
  6022. const profile = document.getElementById('pppoe-server-profile').value;
  6023. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  6024. const onesession = document.getElementById('pppoe-server-onesession').checked;
  6025. try {
  6026. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  6027. method: 'POST',
  6028. headers: { 'Content-Type': 'application/json' },
  6029. body: JSON.stringify({
  6030. enabled,
  6031. service_name: name,
  6032. interface: iface,
  6033. default_profile: profile,
  6034. max_mtu: mtu,
  6035. max_mru: mtu,
  6036. one_session_per_host: onesession
  6037. })
  6038. });
  6039. if (res.ok) {
  6040. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  6041. loadPPPServers();
  6042. fetchData(false);
  6043. } else {
  6044. const err = await res.json();
  6045. showToast('Error', err.message, 'error');
  6046. }
  6047. } catch (err) {
  6048. showToast('Error', err.message, 'error');
  6049. }
  6050. }
  6051. async function savePPTPServerConfig(e) {
  6052. e.preventDefault();
  6053. const enabled = document.getElementById('pptp-server-enabled').checked;
  6054. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  6055. const profile = document.getElementById('pptp-server-profile').value;
  6056. const mppe = document.getElementById('pptp-server-mppe').checked;
  6057. try {
  6058. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  6059. method: 'POST',
  6060. headers: { 'Content-Type': 'application/json' },
  6061. body: JSON.stringify({
  6062. enabled,
  6063. port,
  6064. default_profile: profile,
  6065. require_mppe: mppe
  6066. })
  6067. });
  6068. if (res.ok) {
  6069. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  6070. loadPPPServers();
  6071. fetchData(false);
  6072. } else {
  6073. const err = await res.json();
  6074. showToast('Error', err.message, 'error');
  6075. }
  6076. } catch (err) {
  6077. showToast('Error', err.message, 'error');
  6078. }
  6079. }
  6080. async function saveL2TPServerConfig(e) {
  6081. e.preventDefault();
  6082. const enabled = document.getElementById('l2tp-server-enabled').checked;
  6083. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  6084. const profile = document.getElementById('l2tp-server-profile').value;
  6085. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  6086. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  6087. try {
  6088. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  6089. method: 'POST',
  6090. headers: { 'Content-Type': 'application/json' },
  6091. body: JSON.stringify({
  6092. enabled,
  6093. port,
  6094. default_profile: profile,
  6095. use_ipsec: useipsec,
  6096. ipsec_secret: psk
  6097. })
  6098. });
  6099. if (res.ok) {
  6100. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  6101. loadPPPServers();
  6102. fetchData(false);
  6103. } else {
  6104. const err = await res.json();
  6105. showToast('Error', err.message, 'error');
  6106. }
  6107. } catch (err) {
  6108. showToast('Error', err.message, 'error');
  6109. }
  6110. }
  6111. // IPSec Server Modal
  6112. function openIPSecServerModal() {
  6113. loadPPPServers();
  6114. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  6115. }
  6116. function closeIPSecServerModal() {
  6117. document.getElementById('ipsec-server-modal').classList.add('hidden');
  6118. }
  6119. async function submitSaveIPSecServer(e) {
  6120. e.preventDefault();
  6121. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  6122. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  6123. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  6124. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  6125. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  6126. try {
  6127. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  6128. method: 'POST',
  6129. headers: { 'Content-Type': 'application/json' },
  6130. body: JSON.stringify({
  6131. enabled,
  6132. preshared_key: psk,
  6133. pool_address: pool,
  6134. dns_servers: dns,
  6135. local_subnet: subnet
  6136. })
  6137. });
  6138. if (res.ok) {
  6139. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  6140. closeIPSecServerModal();
  6141. loadPPPServers();
  6142. fetchData(false);
  6143. } else {
  6144. const err = await res.json();
  6145. showToast('Error', err.message, 'error');
  6146. }
  6147. } catch (err) {
  6148. showToast('Error', err.message, 'error');
  6149. }
  6150. }
  6151. // WireGuard Client Config Viewer
  6152. let currentWGClientConf = '';
  6153. async function openWGClientConfModal(iface, clientIP) {
  6154. try {
  6155. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  6156. method: 'POST',
  6157. headers: { 'Content-Type': 'application/json' },
  6158. body: JSON.stringify({
  6159. interface: iface,
  6160. address: clientIP || '10.10.0.2/32',
  6161. dns: '1.1.1.1, 8.8.8.8'
  6162. })
  6163. });
  6164. if (res.ok) {
  6165. const data = await res.json();
  6166. currentWGClientConf = data.config;
  6167. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  6168. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  6169. } else {
  6170. const err = await res.json();
  6171. showToast('Error', err.message, 'error');
  6172. }
  6173. } catch (err) {
  6174. showToast('Error', err.message, 'error');
  6175. }
  6176. }
  6177. function closeWGClientConfModal() {
  6178. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  6179. }
  6180. function copyWGClientConf() {
  6181. if (!currentWGClientConf) return;
  6182. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  6183. }
  6184. function downloadWGClientConf() {
  6185. if (!currentWGClientConf) return;
  6186. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  6187. const a = document.createElement('a');
  6188. a.href = URL.createObjectURL(blob);
  6189. a.download = 'wireguard-client.conf';
  6190. document.body.appendChild(a);
  6191. a.click();
  6192. document.body.removeChild(a);
  6193. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  6194. }
  6195. // =========================================================================
  6196. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  6197. // =========================================================================
  6198. state.activeDynSubTab = 'bgp-peers';
  6199. state.activeBgpSubTab = 'bgp-peers';
  6200. state.activeOspfSubTab = 'ospf-ifaces';
  6201. state.bgpInstance = null;
  6202. state.bgpPeers = [];
  6203. state.bgpNets = [];
  6204. state.bgpRoutes = [];
  6205. state.ospfInstance = null;
  6206. state.ospfInterfaces = [];
  6207. state.ospfAreas = [];
  6208. state.ospfNeighbors = [];
  6209. state.ospfRoutes = [];
  6210. function switchBgpSubTab(subTab) {
  6211. state.activeBgpSubTab = subTab;
  6212. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes'];
  6213. tabs.forEach(t => {
  6214. const el = document.getElementById(`dyn-subtab-${t}`);
  6215. const btn = document.getElementById(`bgp-subtab-btn-${t}`);
  6216. if (el) el.classList.toggle('hidden', t !== subTab);
  6217. if (btn) {
  6218. if (t === subTab) {
  6219. 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';
  6220. } else {
  6221. 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';
  6222. }
  6223. }
  6224. });
  6225. }
  6226. function switchOspfSubTab(subTab) {
  6227. state.activeOspfSubTab = subTab;
  6228. const tabs = ['ospf-ifaces', 'ospf-areas', 'ospf-nbrs', 'ospf-routes'];
  6229. tabs.forEach(t => {
  6230. const el = document.getElementById(`dyn-subtab-${t}`);
  6231. const btn = document.getElementById(`ospf-subtab-btn-${t}`);
  6232. if (el) el.classList.toggle('hidden', t !== subTab);
  6233. if (btn) {
  6234. if (t === subTab) {
  6235. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-indigo-500 text-white transition flex items-center gap-2 whitespace-nowrap';
  6236. } else {
  6237. 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';
  6238. }
  6239. }
  6240. });
  6241. }
  6242. function switchDynSubTab(subTab) {
  6243. if (subTab.startsWith('bgp')) {
  6244. if (state.activeTab !== 'bgp') navigate('bgp');
  6245. switchBgpSubTab(subTab);
  6246. } else if (subTab.startsWith('ospf')) {
  6247. if (state.activeTab !== 'ospf') navigate('ospf');
  6248. switchOspfSubTab(subTab);
  6249. }
  6250. }
  6251. async function loadDynamicRouting(showToastMsg = false) {
  6252. try {
  6253. const fetchSafeJson = async (url) => {
  6254. try {
  6255. const r = await fetch(url);
  6256. return r.ok ? await r.json() : null;
  6257. } catch (e) {
  6258. return null;
  6259. }
  6260. };
  6261. const [sum, bgpInst, bgpPeers, bgpNets, bgpRoutes, ospfInst, ospfIfaces, ospfAreas, ospfNbrs, ospfRoutes, filters] = await Promise.all([
  6262. fetchSafeJson(`${API_BASE}/routing/dynamic/summary`),
  6263. fetchSafeJson(`${API_BASE}/routing/bgp/instance`),
  6264. fetchSafeJson(`${API_BASE}/routing/bgp/peers`),
  6265. fetchSafeJson(`${API_BASE}/routing/bgp/networks`),
  6266. fetchSafeJson(`${API_BASE}/routing/bgp/routes`),
  6267. fetchSafeJson(`${API_BASE}/routing/ospf/instance`),
  6268. fetchSafeJson(`${API_BASE}/routing/ospf/interfaces`),
  6269. fetchSafeJson(`${API_BASE}/routing/ospf/areas`),
  6270. fetchSafeJson(`${API_BASE}/routing/ospf/neighbors`),
  6271. fetchSafeJson(`${API_BASE}/routing/ospf/routes`),
  6272. fetchSafeJson(`${API_BASE}/routing/filters`)
  6273. ]);
  6274. if (sum) state.dynSummary = sum;
  6275. if (bgpInst) state.bgpInstance = bgpInst;
  6276. if (bgpPeers) state.bgpPeers = bgpPeers;
  6277. if (bgpNets) state.bgpNets = bgpNets;
  6278. if (bgpRoutes) state.bgpRoutes = bgpRoutes;
  6279. if (ospfInst) state.ospfInstance = ospfInst;
  6280. if (ospfIfaces) state.ospfInterfaces = ospfIfaces;
  6281. if (ospfAreas) state.ospfAreas = ospfAreas;
  6282. if (ospfNbrs) state.ospfNeighbors = ospfNbrs;
  6283. if (ospfRoutes) state.ospfRoutes = ospfRoutes;
  6284. if (filters) state.routingFilters = filters;
  6285. try { renderBgpStatusPill(); } catch(e) { console.error('renderBgpStatusPill error:', e); }
  6286. try { renderBgpPeers(); } catch(e) { console.error('renderBgpPeers error:', e); }
  6287. try { renderBgpNetworks(); } catch(e) { console.error('renderBgpNetworks error:', e); }
  6288. try { renderBgpRoutes(); } catch(e) { console.error('renderBgpRoutes error:', e); }
  6289. try { renderOspfStatusPill(); } catch(e) { console.error('renderOspfStatusPill error:', e); }
  6290. try { renderOspfInterfaces(); } catch(e) { console.error('renderOspfInterfaces error:', e); }
  6291. try { renderOspfAreas(); } catch(e) { console.error('renderOspfAreas error:', e); }
  6292. try { renderOspfNeighbors(); } catch(e) { console.error('renderOspfNeighbors error:', e); }
  6293. try { renderOspfRoutes(); } catch(e) { console.error('renderOspfRoutes error:', e); }
  6294. try { renderRoutingFilters(); } catch(e) { console.error('renderRoutingFilters error:', e); }
  6295. try { updateBadges(); } catch(e) { console.error('updateBadges error:', e); }
  6296. if (showToastMsg) showToast('Refreshed', 'Dynamic routing telemetry updated', 'info');
  6297. } catch (err) {
  6298. console.error('Failed to load dynamic routing:', err);
  6299. if (showToastMsg) showToast('Notice', 'Unable to refresh dynamic routing telemetry', 'warning');
  6300. }
  6301. }
  6302. function renderBgpStatusPill() {
  6303. const pill = document.getElementById('bgp-live-status-pill');
  6304. if (!pill) return;
  6305. const inst = state.bgpInstance;
  6306. if (!inst || !inst.enabled) {
  6307. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  6308. pill.innerText = 'BGP DISABLED';
  6309. } else if (inst.running) {
  6310. 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';
  6311. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  6312. } else {
  6313. 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';
  6314. pill.innerText = 'BGP STARTING...';
  6315. }
  6316. }
  6317. function renderBgpPeers() {
  6318. const tbody = document.getElementById('bgp-peers-table-body');
  6319. if (!tbody) return;
  6320. const empty = document.getElementById('bgp-peers-empty');
  6321. const countBadge = document.getElementById('bgp-peers-count-badge');
  6322. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  6323. const peers = state.bgpPeers || [];
  6324. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  6325. if (navBadge) navBadge.innerText = peers.length;
  6326. if (peers.length === 0) {
  6327. tbody.innerHTML = '';
  6328. if (empty) empty.classList.remove('hidden');
  6329. return;
  6330. }
  6331. if (empty) empty.classList.add('hidden');
  6332. tbody.innerHTML = peers.map(p => {
  6333. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  6334. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  6335. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  6336. let stateBadge = '';
  6337. if (p.disabled) {
  6338. 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>';
  6339. } else if (p.state === 'Established') {
  6340. 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>';
  6341. } else if (p.state === 'Connect' || p.state === 'Active') {
  6342. 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>`;
  6343. } else {
  6344. 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>`;
  6345. }
  6346. return `
  6347. <tr class="hover:bg-slate-800/40 transition">
  6348. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  6349. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  6350. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  6351. <td class="py-2.5 px-3 font-bold text-slate-200">AS ${p.remote_as}</td>
  6352. <td class="py-2.5 px-3">${stateBadge}</td>
  6353. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  6354. <td class="py-2.5 px-3 text-slate-300">
  6355. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  6356. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  6357. </td>
  6358. <td class="py-2.5 px-3 font-mono text-[11px] whitespace-nowrap">
  6359. ${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> ` : ''}
  6360. ${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>` : ''}
  6361. ${!p.in_filter && !p.out_filter ? '<span class="text-slate-600">-</span>' : ''}
  6362. </td>
  6363. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  6364. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  6365. <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'}">
  6366. ${p.disabled ? 'Enable' : 'Disable'}
  6367. </button>
  6368. <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">
  6369. Edit
  6370. </button>
  6371. <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">
  6372. Delete
  6373. </button>
  6374. </td>
  6375. </tr>
  6376. `;
  6377. }).join('');
  6378. }
  6379. function renderBgpNetworks() {
  6380. const tbody = document.getElementById('bgp-nets-table-body');
  6381. if (!tbody) return;
  6382. const empty = document.getElementById('bgp-nets-empty');
  6383. const countBadge = document.getElementById('bgp-nets-count-badge');
  6384. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  6385. const nets = state.bgpNets || [];
  6386. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  6387. if (navBadge) navBadge.innerText = nets.length;
  6388. if (nets.length === 0) {
  6389. tbody.innerHTML = '';
  6390. if (empty) empty.classList.remove('hidden');
  6391. return;
  6392. }
  6393. if (empty) empty.classList.add('hidden');
  6394. tbody.innerHTML = nets.map(n => `
  6395. <tr class="hover:bg-slate-800/40 transition">
  6396. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  6397. <td class="py-2.5 px-3">
  6398. ${n.disabled
  6399. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  6400. : '<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>'}
  6401. </td>
  6402. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  6403. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  6404. <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">
  6405. Delete
  6406. </button>
  6407. </td>
  6408. </tr>
  6409. `).join('');
  6410. }
  6411. function renderBgpRoutes() {
  6412. const tbody = document.getElementById('bgp-routes-table-body');
  6413. if (!tbody) return;
  6414. const empty = document.getElementById('bgp-routes-empty');
  6415. const countBadge = document.getElementById('bgp-routes-count-badge');
  6416. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  6417. const routes = state.bgpRoutes || [];
  6418. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  6419. if (navBadge) navBadge.innerText = routes.length;
  6420. if (routes.length === 0) {
  6421. tbody.innerHTML = '';
  6422. if (empty) empty.classList.remove('hidden');
  6423. return;
  6424. }
  6425. if (empty) empty.classList.add('hidden');
  6426. tbody.innerHTML = routes.map(r => `
  6427. <tr class="hover:bg-slate-800/40 transition">
  6428. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  6429. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  6430. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  6431. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  6432. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  6433. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  6434. </tr>
  6435. `).join('');
  6436. }
  6437. function renderOspfStatusPill() {
  6438. const pill = document.getElementById('ospf-live-status-pill');
  6439. if (!pill) return;
  6440. const inst = state.ospfInstance;
  6441. if (!inst || !inst.enabled) {
  6442. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  6443. pill.innerText = 'OSPF DISABLED';
  6444. } else if (inst.running) {
  6445. 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';
  6446. pill.innerText = `OSPF ACTIVE (ID: ${inst.router_id || 'Auto'})`;
  6447. } else {
  6448. 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';
  6449. pill.innerText = 'OSPF STARTING...';
  6450. }
  6451. }
  6452. function renderOspfInterfaces() {
  6453. const tbody = document.getElementById('ospf-ifaces-table-body');
  6454. if (!tbody) return;
  6455. const empty = document.getElementById('ospf-ifaces-empty');
  6456. const countBadge = document.getElementById('ospf-ifaces-count-badge');
  6457. const navBadge = document.getElementById('dyn-badge-ospf-ifaces');
  6458. const ifaces = state.ospfInterfaces || [];
  6459. if (countBadge) countBadge.innerText = `${ifaces.length} Interfaces`;
  6460. if (navBadge) navBadge.innerText = ifaces.length;
  6461. if (ifaces.length === 0) {
  6462. tbody.innerHTML = '';
  6463. if (empty) empty.classList.remove('hidden');
  6464. return;
  6465. }
  6466. if (empty) empty.classList.add('hidden');
  6467. tbody.innerHTML = ifaces.map(i => {
  6468. let flagA = !i.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  6469. let flagP = i.passive ? '<span class="text-amber-400 font-bold ml-1" title="Passive">P</span>' : '';
  6470. let flagX = i.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  6471. return `
  6472. <tr class="hover:bg-slate-800/40 transition">
  6473. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagP}${flagX}</td>
  6474. <td class="py-2.5 px-3 font-semibold text-white font-mono">${escapeHtml(i.network)}</td>
  6475. <td class="py-2.5 px-3 text-indigo-300 font-bold">Area ${escapeHtml(i.area)}</td>
  6476. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(i.interface || 'Any')}</td>
  6477. <td class="py-2.5 px-3 text-slate-300">${i.cost}</td>
  6478. <td class="py-2.5 px-3 text-slate-300">${i.priority}</td>
  6479. <td class="py-2.5 px-3 text-slate-400">${i.hello_interval}s / ${i.dead_interval}s</td>
  6480. <td class="py-2.5 px-3 text-slate-300 uppercase">${escapeHtml(i.auth_type || 'none')}</td>
  6481. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(i.comment || '')}</td>
  6482. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  6483. <button onclick="toggleOspfInterfaceState('${i.id}', ${!i.disabled})" class="px-2 py-1 rounded text-[11px] ${i.disabled ? 'bg-emerald-950 hover:bg-emerald-900 text-emerald-400 border border-emerald-800/50' : 'bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700'}">
  6484. ${i.disabled ? 'Enable' : 'Disable'}
  6485. </button>
  6486. <button onclick="openEditOspfInterfaceModal('${i.id}')" class="px-2 py-1 rounded text-[11px] bg-slate-800 hover:bg-slate-700 text-indigo-300 border border-slate-700">
  6487. Edit
  6488. </button>
  6489. <button onclick="deleteOspfInterface('${i.id}')" class="px-2 py-1 rounded text-[11px] bg-rose-950/60 hover:bg-rose-900 text-rose-300 border border-rose-900/50">
  6490. Delete
  6491. </button>
  6492. </td>
  6493. </tr>
  6494. `;
  6495. }).join('');
  6496. }
  6497. function renderOspfAreas() {
  6498. const tbody = document.getElementById('ospf-areas-table-body');
  6499. if (!tbody) return;
  6500. const countBadge = document.getElementById('ospf-areas-count-badge');
  6501. const navBadge = document.getElementById('dyn-badge-ospf-areas');
  6502. const areas = state.ospfAreas || [];
  6503. if (countBadge) countBadge.innerText = `${areas.length} Areas`;
  6504. if (navBadge) navBadge.innerText = areas.length;
  6505. tbody.innerHTML = areas.map(a => `
  6506. <tr class="hover:bg-slate-800/40 transition">
  6507. <td class="py-2.5 px-3 font-semibold text-white font-mono">${escapeHtml(a.name)}</td>
  6508. <td class="py-2.5 px-3 font-bold text-indigo-300">${escapeHtml(a.area_id)}</td>
  6509. <td class="py-2.5 px-3 text-slate-300 uppercase">${escapeHtml(a.area_type || 'default')}</td>
  6510. <td class="py-2.5 px-3 text-slate-400 font-sans">${escapeHtml(a.comment || '')}</td>
  6511. <td class="py-2.5 px-3 text-right font-sans">
  6512. <button onclick="deleteOspfArea('${a.id}')" class="px-2 py-1 rounded text-[11px] bg-rose-950/60 hover:bg-rose-900 text-rose-300 border border-rose-900/50">
  6513. Delete
  6514. </button>
  6515. </td>
  6516. </tr>
  6517. `).join('');
  6518. }
  6519. function renderOspfNeighbors() {
  6520. const tbody = document.getElementById('ospf-nbrs-table-body');
  6521. if (!tbody) return;
  6522. const empty = document.getElementById('ospf-nbrs-empty');
  6523. const countBadge = document.getElementById('ospf-nbrs-count-badge');
  6524. const navBadge = document.getElementById('dyn-badge-ospf-nbrs');
  6525. const nbrs = state.ospfNeighbors || [];
  6526. if (countBadge) countBadge.innerText = `${nbrs.length} Neighbors`;
  6527. if (navBadge) navBadge.innerText = nbrs.length;
  6528. if (nbrs.length === 0) {
  6529. tbody.innerHTML = '';
  6530. if (empty) empty.classList.remove('hidden');
  6531. return;
  6532. }
  6533. if (empty) empty.classList.add('hidden');
  6534. tbody.innerHTML = nbrs.map(n => {
  6535. let stateBadge = '';
  6536. if (n.state && (n.state.startsWith('Full') || n.state.includes('DR') || n.state.includes('Backup'))) {
  6537. stateBadge = `<span class="px-2 py-0.5 rounded-full text-[10px] font-sans font-medium bg-emerald-500/10 text-emerald-400 border border-emerald-500/20">${escapeHtml(n.state)}</span>`;
  6538. } else {
  6539. stateBadge = `<span class="px-2 py-0.5 rounded-full text-[10px] font-sans font-medium bg-amber-500/10 text-amber-400 border border-amber-500/20">${escapeHtml(n.state || 'Unknown')}</span>`;
  6540. }
  6541. return `
  6542. <tr class="hover:bg-slate-800/40 transition">
  6543. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(n.neighbor_id)}</td>
  6544. <td class="py-2.5 px-3 text-indigo-300 font-bold">${escapeHtml(n.address)}</td>
  6545. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(n.interface)}</td>
  6546. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(n.area || '0.0.0.0')}</td>
  6547. <td class="py-2.5 px-3">${stateBadge}</td>
  6548. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(n.dead_timer || '-')}</td>
  6549. </tr>
  6550. `;
  6551. }).join('');
  6552. }
  6553. function renderOspfRoutes() {
  6554. const tbody = document.getElementById('ospf-routes-table-body');
  6555. if (!tbody) return;
  6556. const empty = document.getElementById('ospf-routes-empty');
  6557. const countBadge = document.getElementById('ospf-routes-count-badge');
  6558. const navBadge = document.getElementById('dyn-badge-ospf-routes');
  6559. const routes = state.ospfRoutes || [];
  6560. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  6561. if (navBadge) navBadge.innerText = routes.length;
  6562. if (routes.length === 0) {
  6563. tbody.innerHTML = '';
  6564. if (empty) empty.classList.remove('hidden');
  6565. return;
  6566. }
  6567. if (empty) empty.classList.add('hidden');
  6568. tbody.innerHTML = routes.map(r => `
  6569. <tr class="hover:bg-slate-800/40 transition">
  6570. <td class="py-2.5 px-3 font-semibold text-white font-mono">${escapeHtml(r.prefix)}</td>
  6571. <td class="py-2.5 px-3 text-slate-300">${escapeHtml(r.route_type || 'Network')}</td>
  6572. <td class="py-2.5 px-3 text-slate-300">${r.cost}</td>
  6573. <td class="py-2.5 px-3 text-indigo-300 font-bold">Area ${escapeHtml(r.area || '0.0.0.0')}</td>
  6574. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(r.next_hop || r.interface || '-')}</td>
  6575. </tr>
  6576. `).join('');
  6577. }
  6578. // BGP Modals & Actions
  6579. function openBgpInstanceModal() {
  6580. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  6581. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  6582. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  6583. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  6584. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  6585. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  6586. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  6587. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  6588. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  6589. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  6590. }
  6591. function closeBgpInstanceModal() {
  6592. document.getElementById('bgp-instance-modal').classList.add('hidden');
  6593. }
  6594. async function submitBgpInstance(e) {
  6595. e.preventDefault();
  6596. const payload = {
  6597. enabled: document.getElementById('modal-bgp-enabled').checked,
  6598. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  6599. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  6600. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  6601. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  6602. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  6603. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  6604. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  6605. };
  6606. try {
  6607. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  6608. method: 'POST',
  6609. headers: { 'Content-Type': 'application/json' },
  6610. body: JSON.stringify(payload)
  6611. });
  6612. if (res.ok) {
  6613. closeBgpInstanceModal();
  6614. showToast('Success', 'BGP instance configuration updated', 'success');
  6615. loadDynamicRouting();
  6616. } else {
  6617. const err = await res.json();
  6618. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  6619. }
  6620. } catch (err) {
  6621. showToast('Error', err.message, 'error');
  6622. }
  6623. }
  6624. function openAddBgpPeerModal() {
  6625. document.getElementById('bgp-peer-form').reset();
  6626. document.getElementById('modal-bgp-peer-id').value = '';
  6627. document.getElementById('bgp-peer-modal-title').innerText = 'Add BGP Peer Connection';
  6628. document.getElementById('modal-bgp-peer-nexthop-self').checked = true;
  6629. const inFilterEl = document.getElementById('modal-bgp-peer-in-filter');
  6630. if (inFilterEl) inFilterEl.value = '';
  6631. const outFilterEl = document.getElementById('modal-bgp-peer-out-filter');
  6632. if (outFilterEl) outFilterEl.value = '';
  6633. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  6634. }
  6635. function openEditBgpPeerModal(id) {
  6636. const p = (state.bgpPeers || []).find(item => item.id === id);
  6637. if (!p) return;
  6638. document.getElementById('modal-bgp-peer-id').value = p.id;
  6639. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  6640. document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  6641. document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  6642. document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  6643. document.getElementById('modal-bgp-peer-password').value = p.password || '';
  6644. document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  6645. document.getElementById('modal-bgp-peer-nexthop-self').checked = !!p.nexthop_self;
  6646. document.getElementById('modal-bgp-peer-passive').checked = !!p.passive;
  6647. document.getElementById('modal-bgp-peer-disabled').checked = !!p.disabled;
  6648. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  6649. const inFilterEl = document.getElementById('modal-bgp-peer-in-filter');
  6650. if (inFilterEl) inFilterEl.value = p.in_filter || '';
  6651. const outFilterEl = document.getElementById('modal-bgp-peer-out-filter');
  6652. if (outFilterEl) outFilterEl.value = p.out_filter || '';
  6653. document.getElementById('bgp-peer-modal-title').innerText = 'Edit BGP Peer Connection';
  6654. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  6655. }
  6656. function closeBgpPeerModal() {
  6657. document.getElementById('bgp-peer-modal').classList.add('hidden');
  6658. }
  6659. async function submitBgpPeer(e) {
  6660. e.preventDefault();
  6661. const payload = {
  6662. id: document.getElementById('modal-bgp-peer-id').value,
  6663. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  6664. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  6665. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10),
  6666. local_address: document.getElementById('modal-bgp-peer-local-addr').value.trim(),
  6667. password: document.getElementById('modal-bgp-peer-password').value,
  6668. multihop: document.getElementById('modal-bgp-peer-multihop').checked,
  6669. nexthop_self: document.getElementById('modal-bgp-peer-nexthop-self').checked,
  6670. passive: document.getElementById('modal-bgp-peer-passive').checked,
  6671. disabled: document.getElementById('modal-bgp-peer-disabled').checked,
  6672. in_filter: (document.getElementById('modal-bgp-peer-in-filter')?.value || '').trim(),
  6673. out_filter: (document.getElementById('modal-bgp-peer-out-filter')?.value || '').trim(),
  6674. comment: document.getElementById('modal-bgp-peer-comment').value.trim()
  6675. };
  6676. try {
  6677. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  6678. method: 'POST',
  6679. headers: { 'Content-Type': 'application/json' },
  6680. body: JSON.stringify(payload)
  6681. });
  6682. if (res.ok) {
  6683. closeBgpPeerModal();
  6684. showToast('Success', 'BGP Peer saved', 'success');
  6685. loadDynamicRouting();
  6686. } else {
  6687. const err = await res.json();
  6688. showToast('Error', err.error || 'Failed to save peer', 'error');
  6689. }
  6690. } catch (err) {
  6691. showToast('Error', err.message, 'error');
  6692. }
  6693. }
  6694. async function deleteBgpPeer(id) {
  6695. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  6696. try {
  6697. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6698. if (res.ok) {
  6699. showToast('Deleted', 'BGP peer removed', 'success');
  6700. loadDynamicRouting();
  6701. }
  6702. } catch (err) {
  6703. showToast('Error', err.message, 'error');
  6704. }
  6705. }
  6706. async function toggleBgpPeerState(id, disabled) {
  6707. try {
  6708. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  6709. method: 'POST',
  6710. headers: { 'Content-Type': 'application/json' },
  6711. body: JSON.stringify({ disabled })
  6712. });
  6713. if (res.ok) {
  6714. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  6715. loadDynamicRouting();
  6716. }
  6717. } catch (err) {
  6718. showToast('Error', err.message, 'error');
  6719. }
  6720. }
  6721. function openAddBgpNetworkModal() {
  6722. document.getElementById('bgp-network-form').reset();
  6723. document.getElementById('modal-bgp-net-id').value = '';
  6724. document.getElementById('bgp-network-modal').classList.remove('hidden');
  6725. }
  6726. function closeBgpNetworkModal() {
  6727. document.getElementById('bgp-network-modal').classList.add('hidden');
  6728. }
  6729. async function submitBgpNetwork(e) {
  6730. e.preventDefault();
  6731. const payload = {
  6732. id: document.getElementById('modal-bgp-net-id').value,
  6733. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  6734. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  6735. disabled: document.getElementById('modal-bgp-net-disabled').checked
  6736. };
  6737. try {
  6738. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  6739. method: 'POST',
  6740. headers: { 'Content-Type': 'application/json' },
  6741. body: JSON.stringify(payload)
  6742. });
  6743. if (res.ok) {
  6744. closeBgpNetworkModal();
  6745. showToast('Success', 'BGP network advertisement saved', 'success');
  6746. loadDynamicRouting();
  6747. } else {
  6748. const err = await res.json();
  6749. showToast('Error', err.error || 'Failed to save network', 'error');
  6750. }
  6751. } catch (err) {
  6752. showToast('Error', err.message, 'error');
  6753. }
  6754. }
  6755. async function deleteBgpNetwork(id) {
  6756. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  6757. try {
  6758. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6759. if (res.ok) {
  6760. showToast('Deleted', 'Network advertisement removed', 'success');
  6761. loadDynamicRouting();
  6762. }
  6763. } catch (err) {
  6764. showToast('Error', err.message, 'error');
  6765. }
  6766. }
  6767. // OSPF Modals & Actions
  6768. function openOspfInstanceModal() {
  6769. const inst = state.ospfInstance || { enabled: false, router_id: '192.168.131.56', default_metric: 10 };
  6770. document.getElementById('modal-ospf-enabled').checked = !!inst.enabled;
  6771. document.getElementById('modal-ospf-router-id').value = inst.router_id || '';
  6772. document.getElementById('modal-ospf-metric').value = inst.default_metric || 10;
  6773. document.getElementById('modal-ospf-redist-conn').checked = !!inst.redistribute_connected;
  6774. document.getElementById('modal-ospf-redist-static').checked = !!inst.redistribute_static;
  6775. document.getElementById('modal-ospf-redist-bgp').checked = !!inst.redistribute_bgp;
  6776. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  6777. }
  6778. function closeOspfInstanceModal() {
  6779. document.getElementById('ospf-instance-modal').classList.add('hidden');
  6780. }
  6781. async function submitOspfInstance(e) {
  6782. e.preventDefault();
  6783. const payload = {
  6784. enabled: document.getElementById('modal-ospf-enabled').checked,
  6785. router_id: document.getElementById('modal-ospf-router-id').value.trim(),
  6786. default_metric: parseInt(document.getElementById('modal-ospf-metric').value, 10),
  6787. redistribute_connected: document.getElementById('modal-ospf-redist-conn').checked,
  6788. redistribute_static: document.getElementById('modal-ospf-redist-static').checked,
  6789. redistribute_bgp: document.getElementById('modal-ospf-redist-bgp').checked
  6790. };
  6791. try {
  6792. const res = await fetch(`${API_BASE}/routing/ospf/instance`, {
  6793. method: 'POST',
  6794. headers: { 'Content-Type': 'application/json' },
  6795. body: JSON.stringify(payload)
  6796. });
  6797. if (res.ok) {
  6798. closeOspfInstanceModal();
  6799. showToast('Success', 'OSPF instance configuration updated', 'success');
  6800. loadDynamicRouting();
  6801. } else {
  6802. const err = await res.json();
  6803. showToast('Error', err.error || 'Failed to update OSPF instance', 'error');
  6804. }
  6805. } catch (err) {
  6806. showToast('Error', err.message, 'error');
  6807. }
  6808. }
  6809. function openAddOspfAreaModal() {
  6810. document.getElementById('ospf-area-form').reset();
  6811. document.getElementById('modal-ospf-area-id').value = '';
  6812. document.getElementById('modal-ospf-area-areaid').value = '0.0.0.0';
  6813. document.getElementById('ospf-area-modal').classList.remove('hidden');
  6814. }
  6815. function closeOspfAreaModal() {
  6816. document.getElementById('ospf-area-modal').classList.add('hidden');
  6817. }
  6818. async function submitOspfArea(e) {
  6819. e.preventDefault();
  6820. const payload = {
  6821. id: document.getElementById('modal-ospf-area-id').value,
  6822. name: document.getElementById('modal-ospf-area-name').value.trim(),
  6823. area_id: document.getElementById('modal-ospf-area-areaid').value.trim(),
  6824. area_type: document.getElementById('modal-ospf-area-type').value,
  6825. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  6826. };
  6827. try {
  6828. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  6829. method: 'POST',
  6830. headers: { 'Content-Type': 'application/json' },
  6831. body: JSON.stringify(payload)
  6832. });
  6833. if (res.ok) {
  6834. closeOspfAreaModal();
  6835. showToast('Success', 'OSPF area saved', 'success');
  6836. loadDynamicRouting();
  6837. } else {
  6838. const err = await res.json();
  6839. showToast('Error', err.error || 'Failed to save area', 'error');
  6840. }
  6841. } catch (err) {
  6842. showToast('Error', err.message, 'error');
  6843. }
  6844. }
  6845. async function deleteOspfArea(id) {
  6846. if (!confirm('Are you sure you want to delete this OSPF area?')) return;
  6847. try {
  6848. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6849. if (res.ok) {
  6850. showToast('Deleted', 'OSPF area removed', 'success');
  6851. loadDynamicRouting();
  6852. }
  6853. } catch (err) {
  6854. showToast('Error', err.message, 'error');
  6855. }
  6856. }
  6857. function populateOspfInterfaceDevices() {
  6858. const select = document.getElementById('modal-ospf-iface-device');
  6859. if (!select) return;
  6860. const current = select.value;
  6861. select.innerHTML = '<option value="">Any matching interface</option>';
  6862. (state.interfaces || []).forEach(iface => {
  6863. select.innerHTML += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)} (${iface.type})</option>`;
  6864. });
  6865. if (current) select.value = current;
  6866. }
  6867. function openAddOspfInterfaceModal() {
  6868. document.getElementById('ospf-interface-form').reset();
  6869. document.getElementById('modal-ospf-iface-id').value = '';
  6870. document.getElementById('modal-ospf-iface-area').value = '0.0.0.0';
  6871. document.getElementById('modal-ospf-iface-cost').value = '10';
  6872. document.getElementById('modal-ospf-iface-priority').value = '1';
  6873. document.getElementById('modal-ospf-iface-hello').value = '10';
  6874. document.getElementById('modal-ospf-iface-dead').value = '40';
  6875. document.getElementById('ospf-interface-modal-title').innerText = 'Add OSPF Interface';
  6876. populateOspfInterfaceDevices();
  6877. document.getElementById('ospf-interface-modal').classList.remove('hidden');
  6878. }
  6879. function openEditOspfInterfaceModal(id) {
  6880. const item = (state.ospfInterfaces || []).find(i => i.id === id);
  6881. if (!item) return;
  6882. populateOspfInterfaceDevices();
  6883. document.getElementById('modal-ospf-iface-id').value = item.id;
  6884. document.getElementById('modal-ospf-iface-net').value = item.network || '';
  6885. document.getElementById('modal-ospf-iface-area').value = item.area || '0.0.0.0';
  6886. document.getElementById('modal-ospf-iface-device').value = item.interface || '';
  6887. document.getElementById('modal-ospf-iface-cost').value = item.cost || 10;
  6888. document.getElementById('modal-ospf-iface-priority').value = item.priority || 1;
  6889. document.getElementById('modal-ospf-iface-hello').value = item.hello_interval || 10;
  6890. document.getElementById('modal-ospf-iface-dead').value = item.dead_interval || 40;
  6891. document.getElementById('modal-ospf-iface-auth-type').value = item.auth_type || 'none';
  6892. document.getElementById('modal-ospf-iface-auth-key').value = item.auth_key || '';
  6893. document.getElementById('modal-ospf-iface-passive').checked = !!item.passive;
  6894. document.getElementById('modal-ospf-iface-disabled').checked = !!item.disabled;
  6895. document.getElementById('modal-ospf-iface-comment').value = item.comment || '';
  6896. document.getElementById('ospf-interface-modal-title').innerText = 'Edit OSPF Interface';
  6897. document.getElementById('ospf-interface-modal').classList.remove('hidden');
  6898. }
  6899. function closeOspfInterfaceModal() {
  6900. document.getElementById('ospf-interface-modal').classList.add('hidden');
  6901. }
  6902. async function submitOspfInterface(e) {
  6903. e.preventDefault();
  6904. const payload = {
  6905. id: document.getElementById('modal-ospf-iface-id').value,
  6906. network: document.getElementById('modal-ospf-iface-net').value.trim(),
  6907. area: document.getElementById('modal-ospf-iface-area').value.trim(),
  6908. interface: document.getElementById('modal-ospf-iface-device').value,
  6909. cost: parseInt(document.getElementById('modal-ospf-iface-cost').value, 10),
  6910. priority: parseInt(document.getElementById('modal-ospf-iface-priority').value, 10),
  6911. hello_interval: parseInt(document.getElementById('modal-ospf-iface-hello').value, 10),
  6912. dead_interval: parseInt(document.getElementById('modal-ospf-iface-dead').value, 10),
  6913. auth_type: document.getElementById('modal-ospf-iface-auth-type').value,
  6914. auth_key: document.getElementById('modal-ospf-iface-auth-key').value,
  6915. passive: document.getElementById('modal-ospf-iface-passive').checked,
  6916. disabled: document.getElementById('modal-ospf-iface-disabled').checked,
  6917. comment: document.getElementById('modal-ospf-iface-comment').value.trim()
  6918. };
  6919. try {
  6920. const res = await fetch(`${API_BASE}/routing/ospf/interfaces`, {
  6921. method: 'POST',
  6922. headers: { 'Content-Type': 'application/json' },
  6923. body: JSON.stringify(payload)
  6924. });
  6925. if (res.ok) {
  6926. closeOspfInterfaceModal();
  6927. showToast('Success', 'OSPF interface template saved', 'success');
  6928. loadDynamicRouting();
  6929. } else {
  6930. const err = await res.json();
  6931. showToast('Error', err.error || 'Failed to save interface', 'error');
  6932. }
  6933. } catch (err) {
  6934. showToast('Error', err.message, 'error');
  6935. }
  6936. }
  6937. async function deleteOspfInterface(id) {
  6938. if (!confirm('Are you sure you want to delete this OSPF interface?')) return;
  6939. try {
  6940. const res = await fetch(`${API_BASE}/routing/ospf/interfaces/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6941. if (res.ok) {
  6942. showToast('Deleted', 'OSPF interface removed', 'success');
  6943. loadDynamicRouting();
  6944. }
  6945. } catch (err) {
  6946. showToast('Error', err.message, 'error');
  6947. }
  6948. }
  6949. async function toggleOspfInterfaceState(id, disabled) {
  6950. try {
  6951. const res = await fetch(`${API_BASE}/routing/ospf/interfaces/${encodeURIComponent(id)}/state`, {
  6952. method: 'POST',
  6953. headers: { 'Content-Type': 'application/json' },
  6954. body: JSON.stringify({ disabled })
  6955. });
  6956. if (res.ok) {
  6957. showToast('Updated', `Interface ${disabled ? 'disabled' : 'enabled'}`, 'success');
  6958. loadDynamicRouting();
  6959. }
  6960. } catch (err) {
  6961. showToast('Error', err.message, 'error');
  6962. }
  6963. }
  6964. // ============================================================================
  6965. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  6966. // ============================================================================
  6967. function switchBridgeSubTab(tab) {
  6968. state.bridgeSubTab = tab;
  6969. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  6970. tabs.forEach(t => {
  6971. const panel = document.getElementById(`bridge-subtab-${t}`);
  6972. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  6973. if (panel) {
  6974. if (t === tab) panel.classList.remove('hidden');
  6975. else panel.classList.add('hidden');
  6976. }
  6977. if (btn) {
  6978. if (t === tab) {
  6979. 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';
  6980. } else {
  6981. 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';
  6982. }
  6983. }
  6984. });
  6985. const addBtn = document.getElementById('bridge-top-action-btn');
  6986. if (addBtn) {
  6987. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  6988. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  6989. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  6990. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  6991. }
  6992. if (tab === 'hosts') loadBridgeHosts();
  6993. }
  6994. function openCurrentBridgeModal() {
  6995. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  6996. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  6997. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  6998. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  6999. }
  7000. async function loadBridge() {
  7001. try {
  7002. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vlanIfacesRes] = await Promise.all([
  7003. fetch(`${API_BASE}/bridge/bridges`),
  7004. fetch(`${API_BASE}/bridge/ports`),
  7005. fetch(`${API_BASE}/bridge/vlans`),
  7006. fetch(`${API_BASE}/bridge/summary`),
  7007. fetch(`${API_BASE}/vpn/eoip`),
  7008. fetch(`${API_BASE}/vlans`)
  7009. ]);
  7010. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  7011. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  7012. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  7013. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  7014. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  7015. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  7016. // Badges & Stats
  7017. const bBridges = document.getElementById('bridge-badge-bridges');
  7018. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  7019. const bPorts = document.getElementById('bridge-badge-ports');
  7020. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  7021. const bVlans = document.getElementById('bridge-badge-vlans');
  7022. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  7023. const bHosts = document.getElementById('bridge-badge-hosts');
  7024. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  7025. const sBr = document.getElementById('bridge-stat-bridges');
  7026. if (sBr) sBr.innerText = (state.bridges || []).length;
  7027. const sPorts = document.getElementById('bridge-stat-ports');
  7028. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  7029. const sHosts = document.getElementById('bridge-stat-hosts');
  7030. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  7031. renderBridges();
  7032. renderBridgePorts();
  7033. renderBridgeVLANs();
  7034. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  7035. } catch (err) {
  7036. console.error('Failed to load bridge subsystem:', err);
  7037. }
  7038. }
  7039. // ----------------- Bridges -----------------
  7040. function renderBridges() {
  7041. const tbody = document.getElementById('bridge-table-body');
  7042. const empty = document.getElementById('bridge-empty-bridges');
  7043. const countBadge = document.getElementById('bridge-count-badge');
  7044. if (!tbody) return;
  7045. tbody.innerHTML = '';
  7046. const bridges = state.bridges || [];
  7047. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  7048. if (bridges.length === 0) {
  7049. empty?.classList.remove('hidden');
  7050. return;
  7051. }
  7052. empty?.classList.add('hidden');
  7053. bridges.forEach((b, idx) => {
  7054. const tr = document.createElement('tr');
  7055. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  7056. // Format IP addresses pill list
  7057. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  7058. if (b.ip_addresses && b.ip_addresses.length > 0) {
  7059. ipsHtml = b.ip_addresses.map(ip => `
  7060. <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">
  7061. <span>${ip}</span>
  7062. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  7063. </span>
  7064. `).join(' ');
  7065. }
  7066. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  7067. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  7068. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  7069. tr.innerHTML = `
  7070. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  7071. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  7072. <td class="py-2.5 px-3 font-bold text-white text-sm">
  7073. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  7074. </td>
  7075. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  7076. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  7077. <td class="py-2.5 px-3">
  7078. <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>
  7079. </td>
  7080. <td class="py-2.5 px-3 text-center">
  7081. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  7082. </td>
  7083. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  7084. <td class="py-2.5 px-3">
  7085. <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>
  7086. </td>
  7087. <td class="py-2.5 px-3">
  7088. <div class="flex items-center gap-1.5 flex-wrap">
  7089. ${ipsHtml}
  7090. <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>
  7091. </div>
  7092. </td>
  7093. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  7094. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  7095. </td>
  7096. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  7097. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  7098. <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>
  7099. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  7100. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  7101. </td>
  7102. `;
  7103. tbody.appendChild(tr);
  7104. });
  7105. }
  7106. function openAddBridgeModal() {
  7107. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  7108. document.getElementById('bridge-modal-id').value = '';
  7109. document.getElementById('bridge-modal-name').value = 'bridge1';
  7110. document.getElementById('bridge-modal-name').disabled = false;
  7111. document.getElementById('bridge-modal-mtu').value = '1500';
  7112. document.getElementById('bridge-modal-mac').value = '';
  7113. document.getElementById('bridge-modal-stp').value = 'rstp';
  7114. document.getElementById('bridge-modal-priority').value = '32768';
  7115. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  7116. document.getElementById('bridge-modal-pvid').value = '1';
  7117. document.getElementById('bridge-modal-fastforward').checked = true;
  7118. document.getElementById('bridge-modal-comment').value = '';
  7119. document.getElementById('bridge-modal-disabled').checked = false;
  7120. toggleBridgeModalVlanFiltering();
  7121. document.getElementById('bridge-modal').classList.remove('hidden');
  7122. }
  7123. function openEditBridgeModal(id) {
  7124. const b = (state.bridges || []).find(x => x.id === id);
  7125. if (!b) return;
  7126. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  7127. document.getElementById('bridge-modal-id').value = b.id;
  7128. document.getElementById('bridge-modal-name').value = b.name;
  7129. document.getElementById('bridge-modal-name').disabled = true;
  7130. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  7131. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  7132. document.getElementById('bridge-modal-stp').value = b.stp || 'rstp';
  7133. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  7134. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  7135. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  7136. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  7137. document.getElementById('bridge-modal-comment').value = b.comment || '';
  7138. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  7139. toggleBridgeModalVlanFiltering();
  7140. document.getElementById('bridge-modal').classList.remove('hidden');
  7141. }
  7142. function closeBridgeModal() {
  7143. document.getElementById('bridge-modal').classList.add('hidden');
  7144. }
  7145. function toggleBridgeModalVlanFiltering() {
  7146. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  7147. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  7148. if (pvidBox) {
  7149. if (chk) pvidBox.classList.remove('opacity-40');
  7150. else pvidBox.classList.add('opacity-40');
  7151. }
  7152. }
  7153. async function submitSaveBridge(e) {
  7154. e.preventDefault();
  7155. const id = document.getElementById('bridge-modal-id').value;
  7156. const name = document.getElementById('bridge-modal-name').value.trim();
  7157. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  7158. const mac = document.getElementById('bridge-modal-mac').value.trim();
  7159. const stp = document.getElementById('bridge-modal-stp').value;
  7160. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  7161. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  7162. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  7163. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  7164. const comment = document.getElementById('bridge-modal-comment').value.trim();
  7165. const disabled = document.getElementById('bridge-modal-disabled').checked;
  7166. try {
  7167. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  7168. method: 'POST',
  7169. headers: { 'Content-Type': 'application/json' },
  7170. body: JSON.stringify({
  7171. id,
  7172. name,
  7173. mtu,
  7174. mac_address: mac,
  7175. stp,
  7176. priority,
  7177. vlan_filtering: vlanFiltering,
  7178. pvid,
  7179. fast_forward: fastForward,
  7180. comment,
  7181. disabled
  7182. })
  7183. });
  7184. if (res.ok) {
  7185. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  7186. closeBridgeModal();
  7187. loadBridge();
  7188. fetchData(false);
  7189. } else {
  7190. const err = await res.json();
  7191. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  7192. }
  7193. } catch (err) {
  7194. showToast('Error', err.message, 'error');
  7195. }
  7196. }
  7197. async function toggleBridgeState(id, disabled) {
  7198. try {
  7199. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  7200. method: 'POST',
  7201. headers: { 'Content-Type': 'application/json' },
  7202. body: JSON.stringify({ disabled })
  7203. });
  7204. if (res.ok) {
  7205. loadBridge();
  7206. fetchData(false);
  7207. }
  7208. } catch (err) {
  7209. showToast('Error', err.message, 'error');
  7210. }
  7211. }
  7212. async function deleteBridge(id) {
  7213. const b = (state.bridges || []).find(x => x.id === id);
  7214. const name = b ? b.name : id;
  7215. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  7216. try {
  7217. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7218. if (res.ok) {
  7219. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  7220. loadBridge();
  7221. fetchData(false);
  7222. } else {
  7223. const err = await res.json();
  7224. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  7225. }
  7226. } catch (err) {
  7227. showToast('Error', err.message, 'error');
  7228. }
  7229. }
  7230. // ----------------- Bridge IP Assignments -----------------
  7231. function openAddBridgeIPModal(id, name) {
  7232. document.getElementById('bridge-ip-modal-id').value = id;
  7233. document.getElementById('bridge-ip-modal-sub').innerText = name;
  7234. document.getElementById('bridge-ip-modal-cidr').value = '';
  7235. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  7236. }
  7237. function closeBridgeIPModal() {
  7238. document.getElementById('bridge-ip-modal').classList.add('hidden');
  7239. }
  7240. async function submitAddBridgeIP(e) {
  7241. e.preventDefault();
  7242. const id = document.getElementById('bridge-ip-modal-id').value;
  7243. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  7244. try {
  7245. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  7246. method: 'POST',
  7247. headers: { 'Content-Type': 'application/json' },
  7248. body: JSON.stringify({ ip })
  7249. });
  7250. if (res.ok) {
  7251. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  7252. closeBridgeIPModal();
  7253. loadBridge();
  7254. fetchData(false);
  7255. } else {
  7256. const err = await res.json();
  7257. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  7258. }
  7259. } catch (err) {
  7260. showToast('Error', err.message, 'error');
  7261. }
  7262. }
  7263. async function deleteBridgeIP(id, ip) {
  7264. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  7265. try {
  7266. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  7267. method: 'DELETE',
  7268. headers: { 'Content-Type': 'application/json' },
  7269. body: JSON.stringify({ ip })
  7270. });
  7271. if (res.ok) {
  7272. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  7273. loadBridge();
  7274. fetchData(false);
  7275. }
  7276. } catch (err) {
  7277. showToast('Error', err.message, 'error');
  7278. }
  7279. }
  7280. // ----------------- Bridge Ports -----------------
  7281. function renderBridgePorts() {
  7282. const tbody = document.getElementById('bridge-ports-table-body');
  7283. const empty = document.getElementById('bridge-empty-ports');
  7284. const countBadge = document.getElementById('bridge-ports-count-badge');
  7285. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  7286. if (!tbody) return;
  7287. tbody.innerHTML = '';
  7288. // Update filter select
  7289. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  7290. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  7291. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  7292. if (ports.length === 0) {
  7293. empty?.classList.remove('hidden');
  7294. return;
  7295. }
  7296. empty?.classList.add('hidden');
  7297. ports.forEach((p, idx) => {
  7298. const tr = document.createElement('tr');
  7299. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  7300. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  7301. tr.innerHTML = `
  7302. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  7303. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  7304. <td class="py-2.5 px-3 font-bold text-white text-sm">
  7305. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  7306. </td>
  7307. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  7308. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  7309. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  7310. <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>
  7311. <td class="py-2.5 px-3">
  7312. ${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>'}
  7313. </td>
  7314. <td class="py-2.5 px-3">
  7315. <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>
  7316. </td>
  7317. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  7318. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  7319. <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>
  7320. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  7321. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  7322. </td>
  7323. `;
  7324. tbody.appendChild(tr);
  7325. });
  7326. }
  7327. function openAddBridgePortModal() {
  7328. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  7329. document.getElementById('bridge-port-modal-id').value = '';
  7330. populateBridgeSelect('bridge-port-modal-bridge');
  7331. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  7332. document.getElementById('bridge-port-modal-pvid').value = '1';
  7333. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  7334. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  7335. document.getElementById('bridge-port-modal-horizon').value = '0';
  7336. document.getElementById('bridge-port-modal-pathcost').value = '10';
  7337. document.getElementById('bridge-port-modal-priority').value = '128';
  7338. document.getElementById('bridge-port-modal-learn').checked = true;
  7339. document.getElementById('bridge-port-modal-comment').value = '';
  7340. document.getElementById('bridge-port-modal-disabled').checked = false;
  7341. document.getElementById('bridge-port-modal').classList.remove('hidden');
  7342. }
  7343. function openEditBridgePortModal(id) {
  7344. const p = (state.bridgePorts || []).find(x => x.id === id);
  7345. if (!p) return;
  7346. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  7347. document.getElementById('bridge-port-modal-id').value = p.id;
  7348. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  7349. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  7350. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  7351. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  7352. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  7353. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  7354. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  7355. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  7356. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  7357. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  7358. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  7359. document.getElementById('bridge-port-modal').classList.remove('hidden');
  7360. }
  7361. function closeBridgePortModal() {
  7362. document.getElementById('bridge-port-modal').classList.add('hidden');
  7363. }
  7364. async function submitSaveBridgePort(e) {
  7365. e.preventDefault();
  7366. const id = document.getElementById('bridge-port-modal-id').value;
  7367. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  7368. const iface = document.getElementById('bridge-port-modal-interface').value;
  7369. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  7370. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  7371. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  7372. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  7373. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  7374. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  7375. const learn = document.getElementById('bridge-port-modal-learn').checked;
  7376. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  7377. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  7378. try {
  7379. const res = await fetch(`${API_BASE}/bridge/ports`, {
  7380. method: 'POST',
  7381. headers: { 'Content-Type': 'application/json' },
  7382. body: JSON.stringify({
  7383. id,
  7384. bridge,
  7385. interface: iface,
  7386. pvid,
  7387. frame_types: frameTypes,
  7388. ingress_filtering: ingressFiltering,
  7389. horizon,
  7390. path_cost: pathCost,
  7391. priority,
  7392. learn,
  7393. comment,
  7394. disabled
  7395. })
  7396. });
  7397. if (res.ok) {
  7398. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  7399. closeBridgePortModal();
  7400. loadBridge();
  7401. fetchData(false);
  7402. } else {
  7403. const err = await res.json();
  7404. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  7405. }
  7406. } catch (err) {
  7407. showToast('Error', err.message, 'error');
  7408. }
  7409. }
  7410. async function toggleBridgePortState(id, disabled) {
  7411. try {
  7412. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  7413. method: 'POST',
  7414. headers: { 'Content-Type': 'application/json' },
  7415. body: JSON.stringify({ disabled })
  7416. });
  7417. if (res.ok) {
  7418. loadBridge();
  7419. fetchData(false);
  7420. }
  7421. } catch (err) {
  7422. showToast('Error', err.message, 'error');
  7423. }
  7424. }
  7425. async function deleteBridgePort(id) {
  7426. const p = (state.bridgePorts || []).find(x => x.id === id);
  7427. const iface = p ? p.interface : id;
  7428. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  7429. try {
  7430. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7431. if (res.ok) {
  7432. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  7433. loadBridge();
  7434. fetchData(false);
  7435. }
  7436. } catch (err) {
  7437. showToast('Error', err.message, 'error');
  7438. }
  7439. }
  7440. // ----------------- Bridge VLANs -----------------
  7441. function renderBridgeVLANs() {
  7442. const tbody = document.getElementById('bridge-vlans-table-body');
  7443. const empty = document.getElementById('bridge-empty-vlans');
  7444. const countBadge = document.getElementById('bridge-vlans-count-badge');
  7445. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  7446. if (!tbody) return;
  7447. tbody.innerHTML = '';
  7448. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  7449. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  7450. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  7451. if (vlans.length === 0) {
  7452. empty?.classList.remove('hidden');
  7453. return;
  7454. }
  7455. empty?.classList.add('hidden');
  7456. vlans.forEach((v, idx) => {
  7457. const tr = document.createElement('tr');
  7458. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  7459. const taggedHtml = (v.tagged && v.tagged.length > 0)
  7460. ? 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(' ')
  7461. : '<span class="text-slate-600">none</span>';
  7462. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  7463. ? 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(' ')
  7464. : '<span class="text-slate-600">none</span>';
  7465. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  7466. tr.innerHTML = `
  7467. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  7468. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  7469. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  7470. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  7471. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  7472. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  7473. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  7474. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  7475. <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>
  7476. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  7477. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  7478. </td>
  7479. `;
  7480. tbody.appendChild(tr);
  7481. });
  7482. }
  7483. function openAddBridgeVLANModal() {
  7484. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  7485. document.getElementById('bridge-vlan-modal-id').value = '';
  7486. populateBridgeSelect('bridge-vlan-modal-bridge');
  7487. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  7488. document.getElementById('bridge-vlan-modal-comment').value = '';
  7489. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  7490. updateBridgeVlanPortCheckboxes();
  7491. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  7492. }
  7493. function openEditBridgeVLANModal(id) {
  7494. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  7495. if (!v) return;
  7496. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  7497. document.getElementById('bridge-vlan-modal-id').value = v.id;
  7498. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  7499. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  7500. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  7501. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  7502. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  7503. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  7504. }
  7505. function closeBridgeVlanModal() {
  7506. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  7507. }
  7508. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  7509. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  7510. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  7511. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  7512. if (!taggedBox || !untaggedBox) return;
  7513. // Ports belonging to the selected bridge
  7514. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  7515. if (memberPorts.length === 0) {
  7516. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  7517. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  7518. return;
  7519. }
  7520. taggedBox.innerHTML = memberPorts.map(p => `
  7521. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  7522. <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">
  7523. <span>${p.interface}</span>
  7524. </label>
  7525. `).join('');
  7526. untaggedBox.innerHTML = memberPorts.map(p => `
  7527. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  7528. <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">
  7529. <span>${p.interface}</span>
  7530. </label>
  7531. `).join('');
  7532. }
  7533. async function submitSaveBridgeVLAN(e) {
  7534. e.preventDefault();
  7535. const id = document.getElementById('bridge-vlan-modal-id').value;
  7536. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  7537. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  7538. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  7539. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  7540. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  7541. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  7542. try {
  7543. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  7544. method: 'POST',
  7545. headers: { 'Content-Type': 'application/json' },
  7546. body: JSON.stringify({
  7547. id,
  7548. bridge,
  7549. vlan_ids: vlanIDs,
  7550. tagged,
  7551. untagged,
  7552. comment,
  7553. disabled
  7554. })
  7555. });
  7556. if (res.ok) {
  7557. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  7558. closeBridgeVlanModal();
  7559. loadBridge();
  7560. } else {
  7561. const err = await res.json();
  7562. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  7563. }
  7564. } catch (err) {
  7565. showToast('Error', err.message, 'error');
  7566. }
  7567. }
  7568. async function toggleBridgeVLANState(id, disabled) {
  7569. try {
  7570. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  7571. method: 'POST',
  7572. headers: { 'Content-Type': 'application/json' },
  7573. body: JSON.stringify({ disabled })
  7574. });
  7575. if (res.ok) loadBridge();
  7576. } catch (err) {
  7577. showToast('Error', err.message, 'error');
  7578. }
  7579. }
  7580. async function deleteBridgeVLAN(id) {
  7581. if (!confirm('Delete this bridge VLAN entry?')) return;
  7582. try {
  7583. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7584. if (res.ok) {
  7585. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  7586. loadBridge();
  7587. }
  7588. } catch (err) {
  7589. showToast('Error', err.message, 'error');
  7590. }
  7591. }
  7592. // ----------------- Hosts / MAC Table -----------------
  7593. async function loadBridgeHosts() {
  7594. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  7595. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  7596. try {
  7597. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  7598. const res = await fetch(url);
  7599. if (res.ok) {
  7600. state.bridgeHosts = await res.json();
  7601. renderBridgeHosts();
  7602. }
  7603. } catch (err) {
  7604. console.error('Failed to load bridge hosts:', err);
  7605. }
  7606. }
  7607. function renderBridgeHosts() {
  7608. const tbody = document.getElementById('bridge-hosts-table-body');
  7609. const empty = document.getElementById('bridge-empty-hosts');
  7610. const countBadge = document.getElementById('bridge-hosts-count-badge');
  7611. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  7612. if (!tbody) return;
  7613. tbody.innerHTML = '';
  7614. const hosts = (state.bridgeHosts || []).filter(h => {
  7615. if (!search) return true;
  7616. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  7617. });
  7618. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  7619. if (hosts.length === 0) {
  7620. empty?.classList.remove('hidden');
  7621. return;
  7622. }
  7623. empty?.classList.add('hidden');
  7624. hosts.forEach(h => {
  7625. const tr = document.createElement('tr');
  7626. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  7627. let flagBadges = '';
  7628. 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>';
  7629. 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>';
  7630. 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>';
  7631. tr.innerHTML = `
  7632. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  7633. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  7634. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  7635. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  7636. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  7637. <td class="py-2.5 px-3">${flagBadges}</td>
  7638. `;
  7639. tbody.appendChild(tr);
  7640. });
  7641. }
  7642. async function flushBridgeHosts() {
  7643. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  7644. if (!selBridge) {
  7645. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  7646. return;
  7647. }
  7648. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  7649. try {
  7650. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  7651. method: 'POST',
  7652. headers: { 'Content-Type': 'application/json' },
  7653. body: JSON.stringify({ bridge: selBridge })
  7654. });
  7655. if (res.ok) {
  7656. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  7657. loadBridgeHosts();
  7658. }
  7659. } catch (err) {
  7660. showToast('Error', err.message, 'error');
  7661. }
  7662. }
  7663. // ----------------- Helpers -----------------
  7664. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  7665. const sel = document.getElementById(selectId);
  7666. if (!sel) return;
  7667. const prevVal = currentVal || sel.value;
  7668. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  7669. (state.bridges || []).forEach(b => {
  7670. const opt = document.createElement('option');
  7671. opt.value = b.name;
  7672. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  7673. if (b.name === prevVal) opt.selected = true;
  7674. sel.appendChild(opt);
  7675. });
  7676. }
  7677. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  7678. const sel = document.getElementById(selectId);
  7679. if (!sel) return;
  7680. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  7681. // 1. Physical Interfaces
  7682. const grpPhys = document.createElement('optgroup');
  7683. grpPhys.label = 'Physical Interfaces';
  7684. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  7685. const opt = document.createElement('option');
  7686. opt.value = i.name;
  7687. opt.innerText = `${i.name} (${i.role || i.type})`;
  7688. if (i.name === currentVal) opt.selected = true;
  7689. grpPhys.appendChild(opt);
  7690. });
  7691. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  7692. // 2. VLAN Sub-interfaces
  7693. const grpVlans = document.createElement('optgroup');
  7694. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  7695. (state.vlans || []).forEach(v => {
  7696. const opt = document.createElement('option');
  7697. opt.value = v.name;
  7698. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  7699. if (v.name === currentVal) opt.selected = true;
  7700. grpVlans.appendChild(opt);
  7701. });
  7702. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  7703. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  7704. const grpEoip = document.createElement('optgroup');
  7705. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  7706. (state.eoipTunnels || []).forEach(t => {
  7707. const opt = document.createElement('option');
  7708. opt.value = t.name;
  7709. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  7710. if (t.name === currentVal) opt.selected = true;
  7711. grpEoip.appendChild(opt);
  7712. });
  7713. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  7714. }
  7715. // -------------------------------------------------------------
  7716. // Routing Filters Management (/routing filter)
  7717. // -------------------------------------------------------------
  7718. function renderRoutingFilters() {
  7719. const tbody = document.getElementById('routing-filters-table-body');
  7720. if (!tbody) return;
  7721. const empty = document.getElementById('routing-filters-empty');
  7722. const countBadge = document.getElementById('routing-filters-count-badge');
  7723. const navBadge = document.getElementById('badge-filters-count');
  7724. const chainSelect = document.getElementById('routing-filter-chain-select');
  7725. const allRules = state.routingFilters || [];
  7726. if (navBadge) navBadge.innerText = allRules.length;
  7727. // Populate chain filter select options dynamically
  7728. if (chainSelect) {
  7729. const currentVal = state.filterChainSelected || 'all';
  7730. const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
  7731. chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
  7732. uniqueChains.map(ch => {
  7733. const count = allRules.filter(r => r.chain === ch).length;
  7734. return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
  7735. }).join('');
  7736. chainSelect.value = currentVal;
  7737. }
  7738. // Filter rules by selected chain
  7739. const filteredRules = (state.filterChainSelected && state.filterChainSelected !== 'all')
  7740. ? allRules.filter(r => r.chain === state.filterChainSelected)
  7741. : allRules.slice();
  7742. // Sort by chain then rule_order
  7743. filteredRules.sort((a, b) => {
  7744. if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
  7745. return (a.rule_order || 0) - (b.rule_order || 0);
  7746. });
  7747. if (countBadge) countBadge.innerText = `${filteredRules.length} Rules`;
  7748. if (filteredRules.length === 0) {
  7749. tbody.innerHTML = '';
  7750. if (empty) empty.classList.remove('hidden');
  7751. return;
  7752. }
  7753. if (empty) empty.classList.add('hidden');
  7754. tbody.innerHTML = filteredRules.map(r => {
  7755. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  7756. const flagX = r.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  7757. let actionBadge = '';
  7758. if (r.action === 'accept') {
  7759. 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>';
  7760. } else if (r.action === 'discard') {
  7761. 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>';
  7762. } else if (r.action === 'reject') {
  7763. 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>';
  7764. } else {
  7765. 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>`;
  7766. }
  7767. // Prefix match
  7768. let matchPfx = '';
  7769. if (r.prefix) {
  7770. matchPfx = `<span class="font-bold text-white">${escapeHtml(r.prefix)}</span>`;
  7771. if (r.prefix_len) {
  7772. matchPfx += ` <span class="text-slate-400 text-[11px] font-normal">[${escapeHtml(r.prefix_len)}]</span>`;
  7773. }
  7774. } else {
  7775. matchPfx = '<span class="text-slate-500 italic">any prefix</span>';
  7776. }
  7777. // Other matches
  7778. const matchExtra = [];
  7779. if (r.match_protocol && r.match_protocol !== 'any') {
  7780. 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>`);
  7781. }
  7782. if (r.match_as_path) {
  7783. 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>`);
  7784. }
  7785. if (r.match_community) {
  7786. 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>`);
  7787. }
  7788. const matchExtraHtml = matchExtra.length > 0 ? matchExtra.join(' ') : '<span class="text-slate-600">-</span>';
  7789. // Set modifications
  7790. const setBadges = [];
  7791. if (r.set_local_pref > 0) {
  7792. 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>`);
  7793. }
  7794. if (r.set_metric > 0) {
  7795. 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>`);
  7796. }
  7797. if (r.set_as_prepend > 0) {
  7798. 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>`);
  7799. }
  7800. if (r.set_community) {
  7801. 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>`);
  7802. }
  7803. if (r.set_next_hop) {
  7804. 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>`);
  7805. }
  7806. const setHtml = setBadges.length > 0 ? setBadges.join(' ') : '<span class="text-slate-600">-</span>';
  7807. return `
  7808. <tr class="hover:bg-slate-800/40 transition">
  7809. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagX}</td>
  7810. <td class="py-2.5 px-3 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  7811. <td class="py-2.5 px-3">
  7812. <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>
  7813. </td>
  7814. <td class="py-2.5 px-3">${actionBadge}</td>
  7815. <td class="py-2.5 px-3 font-mono">${matchPfx}</td>
  7816. <td class="py-2.5 px-3 space-x-1">${matchExtraHtml}</td>
  7817. <td class="py-2.5 px-3 space-x-1 font-mono">${setHtml}</td>
  7818. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  7819. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  7820. <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'}">
  7821. ${r.disabled ? 'Enable' : 'Disable'}
  7822. </button>
  7823. <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">
  7824. Edit
  7825. </button>
  7826. <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">
  7827. Delete
  7828. </button>
  7829. </td>
  7830. </tr>
  7831. `;
  7832. }).join('');
  7833. }
  7834. function filterRoutingFiltersByChain(chain) {
  7835. state.filterChainSelected = chain;
  7836. renderRoutingFilters();
  7837. }
  7838. function openAddRoutingFilterModal(defaultChain = '') {
  7839. const form = document.getElementById('routing-filter-form');
  7840. if (form) form.reset();
  7841. const idEl = document.getElementById('modal-rf-id');
  7842. if (idEl) idEl.value = '';
  7843. const titleEl = document.getElementById('modal-rf-title');
  7844. if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
  7845. const chainEl = document.getElementById('modal-rf-chain');
  7846. if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
  7847. const orderEl = document.getElementById('modal-rf-order');
  7848. if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
  7849. const actEl = document.getElementById('modal-rf-action');
  7850. if (actEl) actEl.value = 'accept';
  7851. const protoEl = document.getElementById('modal-rf-protocol');
  7852. if (protoEl) protoEl.value = 'any';
  7853. const disEl = document.getElementById('modal-rf-disabled');
  7854. if (disEl) disEl.checked = false;
  7855. const modal = document.getElementById('modal-routing-filter');
  7856. if (modal) modal.classList.remove('hidden');
  7857. }
  7858. function openEditRoutingFilterModal(id) {
  7859. const r = (state.routingFilters || []).find(item => item.id === id);
  7860. if (!r) return;
  7861. const idEl = document.getElementById('modal-rf-id');
  7862. if (idEl) idEl.value = r.id;
  7863. const titleEl = document.getElementById('modal-rf-title');
  7864. if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
  7865. const chainEl = document.getElementById('modal-rf-chain');
  7866. if (chainEl) chainEl.value = r.chain || '';
  7867. const orderEl = document.getElementById('modal-rf-order');
  7868. if (orderEl) orderEl.value = r.rule_order || 10;
  7869. const actEl = document.getElementById('modal-rf-action');
  7870. if (actEl) actEl.value = r.action || 'accept';
  7871. const pfxEl = document.getElementById('modal-rf-prefix');
  7872. if (pfxEl) pfxEl.value = r.prefix || '';
  7873. const pfxLenEl = document.getElementById('modal-rf-prefix-len');
  7874. if (pfxLenEl) pfxLenEl.value = r.prefix_len || '';
  7875. const protoEl = document.getElementById('modal-rf-protocol');
  7876. if (protoEl) protoEl.value = r.match_protocol || 'any';
  7877. const aspEl = document.getElementById('modal-rf-as-path');
  7878. if (aspEl) aspEl.value = r.match_as_path || '';
  7879. const commEl = document.getElementById('modal-rf-community');
  7880. if (commEl) commEl.value = r.match_community || '';
  7881. const lpEl = document.getElementById('modal-rf-set-local-pref');
  7882. if (lpEl) lpEl.value = r.set_local_pref || '';
  7883. const metEl = document.getElementById('modal-rf-set-metric');
  7884. if (metEl) metEl.value = r.set_metric || '';
  7885. const prepEl = document.getElementById('modal-rf-set-as-prepend');
  7886. if (prepEl) prepEl.value = r.set_as_prepend || '';
  7887. const setCommEl = document.getElementById('modal-rf-set-community');
  7888. if (setCommEl) setCommEl.value = r.set_community || '';
  7889. const nhEl = document.getElementById('modal-rf-set-next-hop');
  7890. if (nhEl) nhEl.value = r.set_next_hop || '';
  7891. const comEl = document.getElementById('modal-rf-comment');
  7892. if (comEl) comEl.value = r.comment || '';
  7893. const disEl = document.getElementById('modal-rf-disabled');
  7894. if (disEl) disEl.checked = !!r.disabled;
  7895. const modal = document.getElementById('modal-routing-filter');
  7896. if (modal) modal.classList.remove('hidden');
  7897. }
  7898. function closeRoutingFilterModal() {
  7899. const modal = document.getElementById('modal-routing-filter');
  7900. if (modal) modal.classList.add('hidden');
  7901. }
  7902. async function submitRoutingFilter(e) {
  7903. e.preventDefault();
  7904. const payload = {
  7905. id: document.getElementById('modal-rf-id').value,
  7906. chain: document.getElementById('modal-rf-chain').value.trim(),
  7907. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  7908. action: document.getElementById('modal-rf-action').value,
  7909. prefix: document.getElementById('modal-rf-prefix').value.trim(),
  7910. prefix_len: document.getElementById('modal-rf-prefix-len').value.trim(),
  7911. match_protocol: document.getElementById('modal-rf-protocol').value,
  7912. match_as_path: document.getElementById('modal-rf-as-path').value.trim(),
  7913. match_community: document.getElementById('modal-rf-community').value.trim(),
  7914. set_local_pref: parseInt(document.getElementById('modal-rf-set-local-pref').value, 10) || 0,
  7915. set_metric: parseInt(document.getElementById('modal-rf-set-metric').value, 10) || 0,
  7916. set_as_prepend: parseInt(document.getElementById('modal-rf-set-as-prepend').value, 10) || 0,
  7917. set_community: document.getElementById('modal-rf-set-community').value.trim(),
  7918. set_next_hop: document.getElementById('modal-rf-set-next-hop').value.trim(),
  7919. comment: document.getElementById('modal-rf-comment').value.trim(),
  7920. disabled: document.getElementById('modal-rf-disabled').checked
  7921. };
  7922. try {
  7923. const res = await fetch(`${API_BASE}/routing/filters`, {
  7924. method: 'POST',
  7925. headers: { 'Content-Type': 'application/json' },
  7926. body: JSON.stringify(payload)
  7927. });
  7928. if (res.ok) {
  7929. closeRoutingFilterModal();
  7930. showToast('Success', 'Routing filter rule saved', 'success');
  7931. loadDynamicRouting();
  7932. } else {
  7933. const err = await res.json();
  7934. showToast('Error', err.error || 'Failed to save filter rule', 'error');
  7935. }
  7936. } catch (err) {
  7937. showToast('Error', err.message, 'error');
  7938. }
  7939. }
  7940. async function deleteRoutingFilter(id) {
  7941. if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
  7942. try {
  7943. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7944. if (res.ok) {
  7945. showToast('Deleted', 'Routing filter rule removed', 'info');
  7946. loadDynamicRouting();
  7947. } else {
  7948. const err = await res.json();
  7949. showToast('Error', err.error || 'Failed to delete rule', 'error');
  7950. }
  7951. } catch (err) {
  7952. showToast('Error', err.message, 'error');
  7953. }
  7954. }
  7955. async function toggleRoutingFilterState(id, disabled) {
  7956. try {
  7957. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
  7958. method: 'POST',
  7959. headers: { 'Content-Type': 'application/json' },
  7960. body: JSON.stringify({ disabled })
  7961. });
  7962. if (res.ok) {
  7963. showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  7964. loadDynamicRouting();
  7965. } else {
  7966. const err = await res.json();
  7967. showToast('Error', err.error || 'Failed to toggle rule state', 'error');
  7968. }
  7969. } catch (err) {
  7970. showToast('Error', err.message, 'error');
  7971. }
  7972. }
  7973. // ==========================================
  7974. // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
  7975. // ==========================================
  7976. function loadToolsView() {
  7977. populateToolsInterfaces();
  7978. switchToolsSubTab(state.activeToolsSubTab || 'ping');
  7979. }
  7980. function populateToolsInterfaces() {
  7981. const pingSel = document.getElementById('tools-ping-iface');
  7982. const traceSel = document.getElementById('tools-tr-iface');
  7983. let opts = '<option value="">Auto (Default Route)</option>';
  7984. if (Array.isArray(state.interfaces)) {
  7985. state.interfaces.forEach(iface => {
  7986. if (iface.name) {
  7987. opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
  7988. }
  7989. });
  7990. }
  7991. if (pingSel) {
  7992. const cur = pingSel.value;
  7993. pingSel.innerHTML = opts;
  7994. if (cur) pingSel.value = cur;
  7995. }
  7996. if (traceSel) {
  7997. const cur = traceSel.value;
  7998. traceSel.innerHTML = opts;
  7999. if (cur) traceSel.value = cur;
  8000. }
  8001. }
  8002. function switchToolsSubTab(subTab) {
  8003. state.activeToolsSubTab = subTab;
  8004. const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
  8005. tabs.forEach(t => {
  8006. const btn = document.getElementById(`tools-subtab-btn-${t}`);
  8007. const view = document.getElementById(`tools-view-${t}`);
  8008. if (btn) {
  8009. if (t === subTab) {
  8010. 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';
  8011. } else {
  8012. 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';
  8013. }
  8014. }
  8015. if (view) {
  8016. if (t === subTab) {
  8017. view.classList.remove('hidden');
  8018. } else {
  8019. view.classList.add('hidden');
  8020. }
  8021. }
  8022. });
  8023. }
  8024. function setPortPreset(port) {
  8025. const input = document.getElementById('tools-port-num');
  8026. if (input) input.value = port;
  8027. }
  8028. let pingAbortController = null;
  8029. let tracerouteAbortController = null;
  8030. function clearPingTable() {
  8031. const tbody = document.getElementById('tools-ping-tbody');
  8032. if (tbody) tbody.innerHTML = '';
  8033. const rawEl = document.getElementById('tools-ping-raw');
  8034. if (rawEl) rawEl.innerText = '';
  8035. const sentEl = document.getElementById('tools-ping-stat-sent');
  8036. if (sentEl) sentEl.innerText = '0';
  8037. const recvEl = document.getElementById('tools-ping-stat-recv');
  8038. if (recvEl) recvEl.innerText = '0';
  8039. const lossEl = document.getElementById('tools-ping-stat-loss');
  8040. if (lossEl) lossEl.innerText = '0%';
  8041. const avgEl = document.getElementById('tools-ping-stat-avg');
  8042. if (avgEl) avgEl.innerText = '0 ms';
  8043. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  8044. if (minMaxEl) minMaxEl.innerText = '-';
  8045. const badge = document.getElementById('tools-ping-status-badge');
  8046. if (badge) {
  8047. badge.className = '';
  8048. badge.innerText = '';
  8049. }
  8050. }
  8051. function clearTracerouteTable() {
  8052. const tbody = document.getElementById('tools-tr-tbody');
  8053. if (tbody) tbody.innerHTML = '';
  8054. const rawEl = document.getElementById('tools-tr-raw');
  8055. if (rawEl) rawEl.innerText = '';
  8056. const statHops = document.getElementById('tools-tr-hops-count');
  8057. if (statHops) statHops.innerText = '0 Hops';
  8058. }
  8059. function resetPingButton() {
  8060. const btn = document.getElementById('tools-ping-btn');
  8061. const btnText = document.getElementById('tools-ping-btn-text');
  8062. const spinner = document.getElementById('tools-ping-spinner');
  8063. if (btn) {
  8064. btn.disabled = false;
  8065. 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';
  8066. }
  8067. if (btnText) btnText.innerText = 'Start Ping';
  8068. if (spinner) spinner.classList.add('hidden');
  8069. }
  8070. function setPingRunningButton() {
  8071. const btn = document.getElementById('tools-ping-btn');
  8072. const btnText = document.getElementById('tools-ping-btn-text');
  8073. const spinner = document.getElementById('tools-ping-spinner');
  8074. if (btn) {
  8075. btn.disabled = false;
  8076. 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';
  8077. }
  8078. if (btnText) btnText.innerText = 'Stop Ping';
  8079. if (spinner) spinner.classList.remove('hidden');
  8080. }
  8081. function resetTracerouteButton() {
  8082. const btn = document.getElementById('tools-tr-btn');
  8083. const btnText = document.getElementById('tools-tr-btn-text');
  8084. const spinner = document.getElementById('tools-tr-spinner');
  8085. if (btn) {
  8086. btn.disabled = false;
  8087. 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';
  8088. }
  8089. if (btnText) btnText.innerText = 'Start Traceroute';
  8090. if (spinner) spinner.classList.add('hidden');
  8091. }
  8092. function setTracerouteRunningButton() {
  8093. const btn = document.getElementById('tools-tr-btn');
  8094. const btnText = document.getElementById('tools-tr-btn-text');
  8095. const spinner = document.getElementById('tools-tr-spinner');
  8096. if (btn) {
  8097. btn.disabled = false;
  8098. 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';
  8099. }
  8100. if (btnText) btnText.innerText = 'Stop Traceroute';
  8101. if (spinner) spinner.classList.remove('hidden');
  8102. }
  8103. async function executePing(e) {
  8104. if (e) e.preventDefault();
  8105. // If already running, clicking the button stops the stream!
  8106. if (pingAbortController) {
  8107. pingAbortController.abort();
  8108. pingAbortController = null;
  8109. resetPingButton();
  8110. showToast('Ping Stopped', 'Live ping stopped by user', 'info');
  8111. return;
  8112. }
  8113. const target = document.getElementById('tools-ping-target')?.value?.trim();
  8114. const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
  8115. const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
  8116. const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '3', 10);
  8117. const iface = document.getElementById('tools-ping-iface')?.value || '';
  8118. const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
  8119. if (!target) {
  8120. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  8121. return;
  8122. }
  8123. clearPingTable();
  8124. const resCard = document.getElementById('tools-ping-results');
  8125. if (resCard) resCard.classList.remove('hidden');
  8126. pingAbortController = new AbortController();
  8127. setPingRunningButton();
  8128. try {
  8129. const res = await fetch(`${API_BASE}/tools/ping/stream`, {
  8130. method: 'POST',
  8131. headers: { 'Content-Type': 'application/json' },
  8132. body: JSON.stringify({
  8133. target,
  8134. count,
  8135. size,
  8136. timeout,
  8137. interface: iface,
  8138. dont_frag: dontFrag
  8139. }),
  8140. signal: pingAbortController.signal
  8141. });
  8142. if (!res.ok) {
  8143. const errText = await res.text();
  8144. showToast('Ping Error', errText || 'Failed to start live ping', 'error');
  8145. resetPingButton();
  8146. pingAbortController = null;
  8147. return;
  8148. }
  8149. const reader = res.body.getReader();
  8150. const decoder = new TextDecoder('utf-8');
  8151. let buffer = '';
  8152. while (true) {
  8153. const { done, value } = await reader.read();
  8154. if (done) break;
  8155. buffer += decoder.decode(value, { stream: true });
  8156. const blocks = buffer.split('\n\n');
  8157. buffer = blocks.pop() || '';
  8158. for (const block of blocks) {
  8159. const trimmed = block.trim();
  8160. if (!trimmed) continue;
  8161. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  8162. try {
  8163. const evt = JSON.parse(line);
  8164. handleLivePingEvent(evt);
  8165. } catch (parseErr) {
  8166. console.warn('Ping SSE parse error:', parseErr, line);
  8167. }
  8168. }
  8169. }
  8170. } catch (err) {
  8171. if (err.name === 'AbortError') {
  8172. // User aborted normally
  8173. } else {
  8174. showToast('Ping Error', err.message, 'error');
  8175. }
  8176. } finally {
  8177. pingAbortController = null;
  8178. resetPingButton();
  8179. }
  8180. }
  8181. function handleLivePingEvent(evt) {
  8182. const sentEl = document.getElementById('tools-ping-stat-sent');
  8183. const recvEl = document.getElementById('tools-ping-stat-recv');
  8184. const lossEl = document.getElementById('tools-ping-stat-loss');
  8185. const avgEl = document.getElementById('tools-ping-stat-avg');
  8186. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  8187. const badge = document.getElementById('tools-ping-status-badge');
  8188. const tbody = document.getElementById('tools-ping-tbody');
  8189. const rawEl = document.getElementById('tools-ping-raw');
  8190. if (evt.raw && rawEl) {
  8191. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  8192. rawEl.scrollTop = rawEl.scrollHeight;
  8193. }
  8194. if (evt.type === 'reply') {
  8195. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  8196. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  8197. if (lossEl && evt.packet_loss_pct !== undefined) {
  8198. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  8199. lossEl.className = evt.packet_loss_pct === 0
  8200. ? 'text-base font-bold font-mono text-emerald-400 mt-1'
  8201. : (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');
  8202. }
  8203. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  8204. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  8205. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  8206. }
  8207. if (badge) {
  8208. if (evt.packet_loss_pct === 0) {
  8209. 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';
  8210. badge.innerText = '100% OK';
  8211. } else {
  8212. 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';
  8213. badge.innerText = `${evt.packet_loss_pct.toFixed(0)}% LOSS`;
  8214. }
  8215. }
  8216. if (tbody) {
  8217. const tr = document.createElement('tr');
  8218. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  8219. tr.innerHTML = `
  8220. <td class="py-2 px-3 text-slate-300">#${evt.seq}</td>
  8221. <td class="py-2 px-3 font-semibold text-white">${escapeHtml(evt.from)}</td>
  8222. <td class="py-2 px-3 text-slate-400">${evt.bytes} bytes</td>
  8223. <td class="py-2 px-3 text-slate-300">${evt.ttl}</td>
  8224. <td class="py-2 px-3 font-bold text-amber-300">${evt.time_ms.toFixed(2)} ms</td>
  8225. <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>
  8226. `;
  8227. tbody.appendChild(tr);
  8228. }
  8229. } else if (evt.type === 'timeout') {
  8230. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  8231. if (lossEl && evt.packet_loss_pct !== undefined) {
  8232. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  8233. 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';
  8234. }
  8235. if (badge) {
  8236. 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';
  8237. badge.innerText = `${evt.packet_loss_pct?.toFixed(0) || 100}% LOSS`;
  8238. }
  8239. if (tbody) {
  8240. const tr = document.createElement('tr');
  8241. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs opacity-75';
  8242. tr.innerHTML = `
  8243. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  8244. <td class="py-2 px-3 font-semibold text-slate-500 italic">Request timed out</td>
  8245. <td class="py-2 px-3 text-slate-600">--</td>
  8246. <td class="py-2 px-3 text-slate-600">--</td>
  8247. <td class="py-2 px-3 font-bold text-slate-500">* * *</td>
  8248. <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>
  8249. `;
  8250. tbody.appendChild(tr);
  8251. }
  8252. } else if (evt.type === 'unreach') {
  8253. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  8254. if (lossEl && evt.packet_loss_pct !== undefined) {
  8255. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  8256. lossEl.className = 'text-base font-bold font-mono text-rose-400 mt-1';
  8257. }
  8258. if (badge) {
  8259. 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';
  8260. badge.innerText = 'UNREACHABLE';
  8261. }
  8262. if (tbody) {
  8263. const tr = document.createElement('tr');
  8264. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  8265. tr.innerHTML = `
  8266. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  8267. <td class="py-2 px-3 font-semibold text-rose-400">${escapeHtml(evt.from || 'Gateway')}</td>
  8268. <td class="py-2 px-3 text-slate-600">--</td>
  8269. <td class="py-2 px-3 text-slate-600">--</td>
  8270. <td class="py-2 px-3 font-bold text-rose-400 text-xs">${escapeHtml(evt.message || 'Unreachable')}</td>
  8271. <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>
  8272. `;
  8273. tbody.appendChild(tr);
  8274. }
  8275. } else if (evt.type === 'stats') {
  8276. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  8277. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  8278. if (lossEl && evt.packet_loss_pct !== undefined) lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  8279. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  8280. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  8281. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  8282. }
  8283. } else if (evt.type === 'done') {
  8284. 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');
  8285. }
  8286. }
  8287. async function executeTraceroute(e) {
  8288. if (e) e.preventDefault();
  8289. if (tracerouteAbortController) {
  8290. tracerouteAbortController.abort();
  8291. tracerouteAbortController = null;
  8292. resetTracerouteButton();
  8293. showToast('Traceroute Stopped', 'Traceroute stopped by user', 'info');
  8294. return;
  8295. }
  8296. const target = document.getElementById('tools-tr-target')?.value?.trim();
  8297. const maxHops = parseInt(document.getElementById('tools-tr-maxhops')?.value || '15', 10);
  8298. const protocol = document.getElementById('tools-tr-proto')?.value || 'icmp';
  8299. const iface = document.getElementById('tools-tr-iface')?.value || '';
  8300. const resolve = document.getElementById('tools-tr-resolve')?.checked || false;
  8301. if (!target) {
  8302. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  8303. return;
  8304. }
  8305. clearTracerouteTable();
  8306. const resCard = document.getElementById('tools-tr-results');
  8307. if (resCard) resCard.classList.remove('hidden');
  8308. tracerouteAbortController = new AbortController();
  8309. setTracerouteRunningButton();
  8310. try {
  8311. const res = await fetch(`${API_BASE}/tools/traceroute/stream`, {
  8312. method: 'POST',
  8313. headers: { 'Content-Type': 'application/json' },
  8314. body: JSON.stringify({
  8315. target,
  8316. max_hops: maxHops,
  8317. protocol,
  8318. interface: iface,
  8319. resolve
  8320. }),
  8321. signal: tracerouteAbortController.signal
  8322. });
  8323. if (!res.ok) {
  8324. const errText = await res.text();
  8325. showToast('Traceroute Error', errText || 'Failed to start traceroute', 'error');
  8326. resetTracerouteButton();
  8327. tracerouteAbortController = null;
  8328. return;
  8329. }
  8330. const reader = res.body.getReader();
  8331. const decoder = new TextDecoder('utf-8');
  8332. let buffer = '';
  8333. while (true) {
  8334. const { done, value } = await reader.read();
  8335. if (done) break;
  8336. buffer += decoder.decode(value, { stream: true });
  8337. const blocks = buffer.split('\n\n');
  8338. buffer = blocks.pop() || '';
  8339. for (const block of blocks) {
  8340. const trimmed = block.trim();
  8341. if (!trimmed) continue;
  8342. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  8343. try {
  8344. const evt = JSON.parse(line);
  8345. handleLiveTracerouteEvent(evt);
  8346. } catch (parseErr) {
  8347. console.warn('Traceroute SSE parse error:', parseErr, line);
  8348. }
  8349. }
  8350. }
  8351. } catch (err) {
  8352. if (err.name === 'AbortError') {
  8353. // User aborted normally
  8354. } else {
  8355. showToast('Traceroute Error', err.message, 'error');
  8356. }
  8357. } finally {
  8358. tracerouteAbortController = null;
  8359. resetTracerouteButton();
  8360. }
  8361. }
  8362. function handleLiveTracerouteEvent(evt) {
  8363. const statHops = document.getElementById('tools-tr-hops-count');
  8364. const tbody = document.getElementById('tools-tr-tbody');
  8365. const rawEl = document.getElementById('tools-tr-raw');
  8366. if (evt.raw && rawEl) {
  8367. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  8368. rawEl.scrollTop = rawEl.scrollHeight;
  8369. }
  8370. if (evt.hops_count !== undefined && statHops) {
  8371. statHops.innerText = `${evt.hops_count} Hops`;
  8372. }
  8373. if (evt.type === 'hop' && evt.hop && tbody) {
  8374. const h = evt.hop;
  8375. const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
  8376. const rtt1 = Array.isArray(h.times_ms) && h.times_ms[0] ? `${h.times_ms[0]} ms` : (isTimeout ? '*' : '--');
  8377. const rtt2 = Array.isArray(h.times_ms) && h.times_ms[1] ? `${h.times_ms[1]} ms` : (isTimeout ? '*' : '--');
  8378. const displayHost = h.host && h.host !== h.ip ? `${escapeHtml(h.host)} (${escapeHtml(h.ip || '')})` : escapeHtml(h.ip || (isTimeout ? 'Request timed out' : '--'));
  8379. const tr = document.createElement('tr');
  8380. tr.className = `hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}`;
  8381. tr.innerHTML = `
  8382. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  8383. <td class="py-2.5 px-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${displayHost}</td>
  8384. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt1)}</td>
  8385. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt2)}</td>
  8386. <td class="py-2.5 px-3 text-right">
  8387. ${isTimeout
  8388. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
  8389. : '<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>'}
  8390. </td>
  8391. `;
  8392. tbody.appendChild(tr);
  8393. } else if (evt.type === 'done') {
  8394. showToast('Traceroute Finished', `Traced ${evt.hops_count || 0} hops`, 'info');
  8395. }
  8396. }
  8397. async function executeMTR(e) {
  8398. if (e) e.preventDefault();
  8399. const target = document.getElementById('tools-mtr-target')?.value?.trim();
  8400. const cycles = parseInt(document.getElementById('tools-mtr-count')?.value || '3', 10);
  8401. if (!target) {
  8402. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  8403. return;
  8404. }
  8405. const btn = document.getElementById('tools-mtr-btn');
  8406. const spinner = document.getElementById('tools-mtr-spinner');
  8407. if (btn) btn.disabled = true;
  8408. if (spinner) spinner.classList.remove('hidden');
  8409. try {
  8410. const res = await fetch(`${API_BASE}/tools/mtr`, {
  8411. method: 'POST',
  8412. headers: { 'Content-Type': 'application/json' },
  8413. body: JSON.stringify({ target, count: cycles })
  8414. });
  8415. const data = await res.json();
  8416. if (!res.ok) {
  8417. showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
  8418. return;
  8419. }
  8420. const resCard = document.getElementById('tools-mtr-results');
  8421. if (resCard) resCard.classList.remove('hidden');
  8422. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  8423. const statHops = document.getElementById('tools-mtr-hops-count');
  8424. if (statHops) statHops.innerText = `${hopsCount} Hops`;
  8425. const tbody = document.getElementById('tools-mtr-tbody');
  8426. if (tbody) {
  8427. if (hopsCount > 0) {
  8428. tbody.innerHTML = data.hops.map(h => {
  8429. 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');
  8430. return `
  8431. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  8432. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  8433. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
  8434. <td class="py-2.5 px-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
  8435. <td class="py-2.5 px-3 text-slate-300">${h.sent}</td>
  8436. <td class="py-2.5 px-3 text-slate-300">${h.last_ms.toFixed(1)}</td>
  8437. <td class="py-2.5 px-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)}</td>
  8438. <td class="py-2.5 px-3 text-emerald-400">${h.best_ms.toFixed(1)}</td>
  8439. <td class="py-2.5 px-3 text-rose-400">${h.wrst_ms.toFixed(1)}</td>
  8440. <td class="py-2.5 px-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
  8441. </tr>
  8442. `;
  8443. }).join('');
  8444. } else {
  8445. tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
  8446. }
  8447. }
  8448. const rawEl = document.getElementById('tools-mtr-raw');
  8449. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  8450. showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
  8451. } catch (err) {
  8452. showToast('MTR Error', err.message, 'error');
  8453. } finally {
  8454. if (btn) btn.disabled = false;
  8455. if (spinner) spinner.classList.add('hidden');
  8456. }
  8457. }
  8458. async function executeDNS(e) {
  8459. if (e) e.preventDefault();
  8460. const domain = document.getElementById('tools-dns-domain')?.value?.trim();
  8461. const type = document.getElementById('tools-dns-type')?.value || 'A';
  8462. const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
  8463. if (!domain) {
  8464. showToast('Input Required', 'Please enter a hostname or domain', 'warning');
  8465. return;
  8466. }
  8467. const btn = document.getElementById('tools-dns-btn');
  8468. const spinner = document.getElementById('tools-dns-spinner');
  8469. if (btn) btn.disabled = true;
  8470. if (spinner) spinner.classList.remove('hidden');
  8471. try {
  8472. const res = await fetch(`${API_BASE}/tools/dns`, {
  8473. method: 'POST',
  8474. headers: { 'Content-Type': 'application/json' },
  8475. body: JSON.stringify({ domain, type, server })
  8476. });
  8477. const data = await res.json();
  8478. if (!res.ok) {
  8479. showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
  8480. return;
  8481. }
  8482. const resCard = document.getElementById('tools-dns-results');
  8483. if (resCard) resCard.classList.remove('hidden');
  8484. const metaEl = document.getElementById('tools-dns-meta');
  8485. if (metaEl) metaEl.innerText = `Resolved in ${data.query_time_ms ?? 0} ms via ${escapeHtml(data.server || 'System DNS')}`;
  8486. const tbody = document.getElementById('tools-dns-tbody');
  8487. if (tbody) {
  8488. if (Array.isArray(data.records) && data.records.length > 0) {
  8489. tbody.innerHTML = data.records.map(r => `
  8490. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  8491. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.name)}</td>
  8492. <td class="py-2.5 px-3 text-slate-400">${r.ttl}s</td>
  8493. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.class || 'IN')}</td>
  8494. <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>
  8495. <td class="py-2.5 px-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
  8496. </tr>
  8497. `).join('');
  8498. } else {
  8499. 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>`;
  8500. }
  8501. }
  8502. const rawEl = document.getElementById('tools-dns-raw');
  8503. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  8504. showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
  8505. } catch (err) {
  8506. showToast('DNS Error', err.message, 'error');
  8507. } finally {
  8508. if (btn) btn.disabled = false;
  8509. if (spinner) spinner.classList.add('hidden');
  8510. }
  8511. }
  8512. async function executePortProbe(e) {
  8513. if (e) e.preventDefault();
  8514. const target = document.getElementById('tools-port-target')?.value?.trim();
  8515. const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
  8516. const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
  8517. if (!target || !port) {
  8518. showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
  8519. return;
  8520. }
  8521. const btn = document.getElementById('tools-port-btn');
  8522. const spinner = document.getElementById('tools-port-spinner');
  8523. if (btn) btn.disabled = true;
  8524. if (spinner) spinner.classList.remove('hidden');
  8525. try {
  8526. const res = await fetch(`${API_BASE}/tools/port-probe`, {
  8527. method: 'POST',
  8528. headers: { 'Content-Type': 'application/json' },
  8529. body: JSON.stringify({ target, port, timeout })
  8530. });
  8531. const data = await res.json();
  8532. if (!res.ok) {
  8533. showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
  8534. return;
  8535. }
  8536. const resCard = document.getElementById('tools-port-results');
  8537. if (resCard) resCard.classList.remove('hidden');
  8538. const banner = document.getElementById('tools-port-banner');
  8539. const icon = document.getElementById('tools-port-icon');
  8540. const title = document.getElementById('tools-port-title');
  8541. const sub = document.getElementById('tools-port-sub');
  8542. const latency = document.getElementById('tools-port-latency');
  8543. if (data.open) {
  8544. if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
  8545. if (icon) {
  8546. 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';
  8547. icon.innerText = '✓';
  8548. }
  8549. if (title) {
  8550. title.className = 'text-sm font-bold text-emerald-300';
  8551. title.innerText = `PORT ${port} OPEN / LISTENING`;
  8552. }
  8553. if (sub) {
  8554. sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
  8555. sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
  8556. }
  8557. if (latency) {
  8558. latency.className = 'text-base font-bold font-mono text-emerald-300';
  8559. latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
  8560. }
  8561. } else {
  8562. if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-800/50 flex items-center justify-between';
  8563. if (icon) {
  8564. 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';
  8565. icon.innerText = '✕';
  8566. }
  8567. if (title) {
  8568. title.className = 'text-sm font-bold text-rose-300';
  8569. title.innerText = `PORT ${port} CLOSED / FILTERED`;
  8570. }
  8571. if (sub) {
  8572. sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
  8573. sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
  8574. }
  8575. if (latency) {
  8576. latency.className = 'text-base font-bold font-mono text-slate-500';
  8577. latency.innerText = '--';
  8578. }
  8579. }
  8580. const rawEl = document.getElementById('tools-port-raw');
  8581. 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'}`);
  8582. showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
  8583. } catch (err) {
  8584. showToast('Probe Error', err.message, 'error');
  8585. } finally {
  8586. if (btn) btn.disabled = false;
  8587. if (spinner) spinner.classList.add('hidden');
  8588. }
  8589. }
  8590. // ==========================================
  8591. // DHCP CLIENT (/ip dhcp-client) CONTROLLER
  8592. // ==========================================
  8593. async function loadDHCPClients(showToastMsg = false) {
  8594. try {
  8595. const [clientsRes, sumRes] = await Promise.all([
  8596. fetch(`${API_BASE}/dhcp/clients`),
  8597. fetch(`${API_BASE}/dhcp/clients/summary`)
  8598. ]);
  8599. if (clientsRes.ok) {
  8600. state.dhcpClients = await clientsRes.json();
  8601. }
  8602. if (sumRes.ok) {
  8603. state.dhcpSummary = await sumRes.json();
  8604. }
  8605. renderDHCPClients();
  8606. updateDHCPSummaryCards();
  8607. const bDhcp = document.getElementById('badge-dhcp-client-count');
  8608. if (bDhcp && state.dhcpSummary) {
  8609. bDhcp.innerText = state.dhcpSummary.total_clients || 0;
  8610. }
  8611. if (showToastMsg) {
  8612. showToast('Refreshed', 'DHCP Client telemetry updated', 'info');
  8613. }
  8614. } catch (err) {
  8615. console.error('Failed to load DHCP clients:', err);
  8616. if (showToastMsg) {
  8617. showToast('Notice', 'Unable to fetch DHCP client status', 'warning');
  8618. }
  8619. }
  8620. }
  8621. function updateDHCPSummaryCards() {
  8622. const sum = state.dhcpSummary || {
  8623. total_clients: (state.dhcpClients || []).length,
  8624. bound_clients: (state.dhcpClients || []).filter(c => c.status === 'bound').length,
  8625. searching_clients: (state.dhcpClients || []).filter(c => c.status === 'searching').length,
  8626. disabled_clients: (state.dhcpClients || []).filter(c => !c.enabled).length
  8627. };
  8628. const totalEl = document.getElementById('dhcp-stat-total');
  8629. const boundEl = document.getElementById('dhcp-stat-bound');
  8630. const searchEl = document.getElementById('dhcp-stat-searching');
  8631. const disEl = document.getElementById('dhcp-stat-disabled');
  8632. if (totalEl) totalEl.innerText = sum.total_clients ?? 0;
  8633. if (boundEl) boundEl.innerText = sum.bound_clients ?? 0;
  8634. if (searchEl) searchEl.innerText = sum.searching_clients ?? 0;
  8635. if (disEl) disEl.innerText = sum.disabled_clients ?? 0;
  8636. }
  8637. function renderDHCPClients() {
  8638. const tbody = document.getElementById('dhcp-clients-tbody');
  8639. const emptyState = document.getElementById('dhcp-clients-empty');
  8640. if (!tbody) return;
  8641. const clients = Array.isArray(state.dhcpClients) ? state.dhcpClients : [];
  8642. if (clients.length === 0) {
  8643. tbody.innerHTML = '';
  8644. if (emptyState) emptyState.classList.remove('hidden');
  8645. return;
  8646. }
  8647. if (emptyState) emptyState.classList.add('hidden');
  8648. tbody.innerHTML = clients.map(c => {
  8649. let statusBadge = '';
  8650. if (!c.enabled) {
  8651. 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>';
  8652. } else if (c.status === 'bound') {
  8653. 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>';
  8654. } else if (c.status === 'searching') {
  8655. 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>';
  8656. } else if (c.status === 'stopped') {
  8657. 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>';
  8658. } else {
  8659. 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>`;
  8660. }
  8661. 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>';
  8662. const gwDisplay = c.gateway ? `<span class="text-slate-300">${escapeHtml(c.gateway)}</span>` : '<span class="text-slate-600">--</span>';
  8663. const srvDisplay = c.dhcp_server ? `<span class="text-slate-300">${escapeHtml(c.dhcp_server)}</span>` : '<span class="text-slate-600">--</span>';
  8664. 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>';
  8665. const expDisplay = c.expires_in ? `<span class="text-purple-300">${escapeHtml(c.expires_in)}</span>` : '<span class="text-slate-600">--</span>';
  8666. // Option flags
  8667. const flags = [];
  8668. 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>');
  8669. 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>');
  8670. 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>');
  8671. 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>`);
  8672. return `
  8673. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 text-xs transition">
  8674. <td class="py-3 px-4">
  8675. <div class="flex items-center gap-2">
  8676. <span class="font-bold text-white text-sm">${escapeHtml(c.interface)}</span>
  8677. ${c.comment ? `<span class="text-[11px] text-slate-400 font-sans italic">(${escapeHtml(c.comment)})</span>` : ''}
  8678. </div>
  8679. </td>
  8680. <td class="py-3 px-4">${statusBadge}</td>
  8681. <td class="py-3 px-4 font-mono">${ipDisplay}</td>
  8682. <td class="py-3 px-4 font-mono">${gwDisplay}</td>
  8683. <td class="py-3 px-4 font-mono">${srvDisplay}</td>
  8684. <td class="py-3 px-4 font-mono text-[11px]">${dnsDisplay}</td>
  8685. <td class="py-3 px-4 font-mono text-[11px]">${expDisplay}</td>
  8686. <td class="py-3 px-4">
  8687. <div class="flex flex-wrap gap-1 font-mono">${flags.join('')}</div>
  8688. </td>
  8689. <td class="py-3 px-4 text-right space-x-1.5 font-sans whitespace-nowrap">
  8690. ${c.enabled ? `
  8691. <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>
  8692. <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>
  8693. <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>
  8694. ` : `
  8695. <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>
  8696. `}
  8697. <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>
  8698. <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>
  8699. </td>
  8700. </tr>
  8701. `;
  8702. }).join('');
  8703. }
  8704. function openDHCPClientModal(clientId = null) {
  8705. const modal = document.getElementById('modal-dhcp-client');
  8706. if (!modal) return;
  8707. const title = document.getElementById('modal-dhcp-title');
  8708. const idInput = document.getElementById('modal-dhcp-id');
  8709. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  8710. const distInput = document.getElementById('modal-dhcp-distance');
  8711. const commentInput = document.getElementById('modal-dhcp-comment');
  8712. const defRouteCheck = document.getElementById('modal-dhcp-def-route');
  8713. const peerDnsCheck = document.getElementById('modal-dhcp-peer-dns');
  8714. const peerNtpCheck = document.getElementById('modal-dhcp-peer-ntp');
  8715. const enabledCheck = document.getElementById('modal-dhcp-enabled');
  8716. // Populate interfaces
  8717. if (ifaceSelect) {
  8718. let opts = '<option value="">Select interface...</option>';
  8719. const allIfaces = state.interfaces || [];
  8720. const allVlans = state.vlans || [];
  8721. const usedIfaces = new Set((state.dhcpClients || []).map(c => c.interface));
  8722. // Group 1: Physical & Bridge Interfaces
  8723. opts += '<optgroup label="Physical & Bridge Interfaces">';
  8724. allIfaces.forEach(i => {
  8725. const isConfigured = usedIfaces.has(i.name) ? ' (Configured)' : '';
  8726. opts += `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} [${escapeHtml(i.role || i.type)}]${isConfigured}</option>`;
  8727. });
  8728. opts += '</optgroup>';
  8729. // Group 2: VLAN Interfaces
  8730. if (allVlans.length > 0) {
  8731. opts += '<optgroup label="802.1Q VLAN Sub-interfaces">';
  8732. allVlans.forEach(v => {
  8733. const isConfigured = usedIfaces.has(v.name) ? ' (Configured)' : '';
  8734. opts += `<option value="${escapeHtml(v.name)}">${escapeHtml(v.name)} (VLAN ${v.vlan_id})${isConfigured}</option>`;
  8735. });
  8736. opts += '</optgroup>';
  8737. }
  8738. ifaceSelect.innerHTML = opts;
  8739. }
  8740. if (clientId) {
  8741. const client = (state.dhcpClients || []).find(c => c.id === clientId);
  8742. if (client) {
  8743. if (title) title.innerText = `Edit DHCP Client: ${client.interface}`;
  8744. if (idInput) idInput.value = client.id;
  8745. if (ifaceSelect) {
  8746. ifaceSelect.value = client.interface;
  8747. ifaceSelect.disabled = true; // interface cannot be changed on edit
  8748. }
  8749. if (distInput) distInput.value = client.default_route_distance || 1;
  8750. if (commentInput) commentInput.value = client.comment || '';
  8751. if (defRouteCheck) defRouteCheck.checked = client.add_default_route !== false;
  8752. if (peerDnsCheck) peerDnsCheck.checked = client.use_peer_dns !== false;
  8753. if (peerNtpCheck) peerNtpCheck.checked = client.use_peer_ntp !== false;
  8754. if (enabledCheck) enabledCheck.checked = client.enabled !== false;
  8755. }
  8756. } else {
  8757. if (title) title.innerText = 'Add DHCP Client';
  8758. if (idInput) idInput.value = '';
  8759. if (ifaceSelect) {
  8760. ifaceSelect.value = '';
  8761. ifaceSelect.disabled = false;
  8762. }
  8763. if (distInput) distInput.value = 1;
  8764. if (commentInput) commentInput.value = '';
  8765. if (defRouteCheck) defRouteCheck.checked = true;
  8766. if (peerDnsCheck) peerDnsCheck.checked = true;
  8767. if (peerNtpCheck) peerNtpCheck.checked = true;
  8768. if (enabledCheck) enabledCheck.checked = true;
  8769. }
  8770. modal.classList.remove('hidden');
  8771. }
  8772. function openDHCPClientModalForIface(ifaceName) {
  8773. openDHCPClientModal();
  8774. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  8775. if (ifaceSelect && ifaceName) {
  8776. ifaceSelect.value = ifaceName;
  8777. }
  8778. }
  8779. function closeDHCPClientModal() {
  8780. const modal = document.getElementById('modal-dhcp-client');
  8781. if (modal) modal.classList.add('hidden');
  8782. }
  8783. async function submitSaveDHCPClient(e) {
  8784. if (e) e.preventDefault();
  8785. const id = document.getElementById('modal-dhcp-id')?.value;
  8786. const iface = document.getElementById('modal-dhcp-iface')?.value?.trim();
  8787. const distance = parseInt(document.getElementById('modal-dhcp-distance')?.value || '1', 10);
  8788. const comment = document.getElementById('modal-dhcp-comment')?.value?.trim() || '';
  8789. const defRoute = document.getElementById('modal-dhcp-def-route')?.checked ?? true;
  8790. const peerDns = document.getElementById('modal-dhcp-peer-dns')?.checked ?? true;
  8791. const peerNtp = document.getElementById('modal-dhcp-peer-ntp')?.checked ?? true;
  8792. const enabled = document.getElementById('modal-dhcp-enabled')?.checked ?? true;
  8793. if (!id && !iface) {
  8794. showToast('Input Required', 'Please select an interface for the DHCP client', 'warning');
  8795. return;
  8796. }
  8797. try {
  8798. let res;
  8799. if (id) {
  8800. // PUT update
  8801. res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  8802. method: 'PUT',
  8803. headers: { 'Content-Type': 'application/json' },
  8804. body: JSON.stringify({
  8805. enabled,
  8806. add_default_route: defRoute,
  8807. default_route_distance: distance,
  8808. use_peer_dns: peerDns,
  8809. use_peer_ntp: peerNtp,
  8810. comment
  8811. })
  8812. });
  8813. } else {
  8814. // POST create
  8815. res = await fetch(`${API_BASE}/dhcp/clients`, {
  8816. method: 'POST',
  8817. headers: { 'Content-Type': 'application/json' },
  8818. body: JSON.stringify({
  8819. interface: iface,
  8820. enabled,
  8821. add_default_route: defRoute,
  8822. default_route_distance: distance,
  8823. use_peer_dns: peerDns,
  8824. use_peer_ntp: peerNtp,
  8825. comment
  8826. })
  8827. });
  8828. }
  8829. const data = await res.json();
  8830. if (!res.ok) {
  8831. showToast('Error', data.error || 'Failed to save DHCP client', 'error');
  8832. return;
  8833. }
  8834. closeDHCPClientModal();
  8835. showToast('Success', id ? 'DHCP Client updated successfully' : `DHCP Client activated on ${iface}`, 'success');
  8836. await loadDHCPClients();
  8837. fetchData(); // refresh interfaces list with new lease/status
  8838. } catch (err) {
  8839. showToast('Error', err.message, 'error');
  8840. }
  8841. }
  8842. async function toggleDHCPClientState(id, enabled) {
  8843. try {
  8844. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/state`, {
  8845. method: 'POST',
  8846. headers: { 'Content-Type': 'application/json' },
  8847. body: JSON.stringify({ enabled })
  8848. });
  8849. const data = await res.json();
  8850. if (!res.ok) {
  8851. showToast('Error', data.error || 'Failed to toggle client state', 'error');
  8852. return;
  8853. }
  8854. showToast('Updated', `DHCP client ${enabled ? 'enabled' : 'disabled'}`, 'info');
  8855. await loadDHCPClients();
  8856. fetchData();
  8857. } catch (err) {
  8858. showToast('Error', err.message, 'error');
  8859. }
  8860. }
  8861. async function renewDHCPClient(id) {
  8862. try {
  8863. showToast('Renewing...', 'Requesting DHCP lease renewal from upstream server', 'info');
  8864. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/renew`, {
  8865. method: 'POST'
  8866. });
  8867. const data = await res.json();
  8868. if (!res.ok) {
  8869. showToast('Error', data.error || 'Failed to renew lease', 'error');
  8870. return;
  8871. }
  8872. showToast('Lease Renewed', 'DHCP renewal signal sent successfully', 'success');
  8873. setTimeout(() => {
  8874. loadDHCPClients();
  8875. fetchData();
  8876. }, 1500);
  8877. } catch (err) {
  8878. showToast('Error', err.message, 'error');
  8879. }
  8880. }
  8881. async function releaseDHCPClient(id) {
  8882. try {
  8883. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/release`, {
  8884. method: 'POST'
  8885. });
  8886. const data = await res.json();
  8887. if (!res.ok) {
  8888. showToast('Error', data.error || 'Failed to release lease', 'error');
  8889. return;
  8890. }
  8891. showToast('Lease Released', 'DHCP lease released from upstream server', 'info');
  8892. await loadDHCPClients();
  8893. fetchData();
  8894. } catch (err) {
  8895. showToast('Error', err.message, 'error');
  8896. }
  8897. }
  8898. async function deleteDHCPClient(id, ifaceName) {
  8899. if (!confirm(`Are you sure you want to remove the DHCP Client on ${ifaceName}? The interface will release its dynamic IP.`)) {
  8900. return;
  8901. }
  8902. try {
  8903. const res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  8904. method: 'DELETE'
  8905. });
  8906. const data = await res.json();
  8907. if (!res.ok) {
  8908. showToast('Error', data.error || 'Failed to delete DHCP client', 'error');
  8909. return;
  8910. }
  8911. showToast('Deleted', `DHCP client removed from ${ifaceName}`, 'info');
  8912. await loadDHCPClients();
  8913. fetchData();
  8914. } catch (err) {
  8915. showToast('Error', err.message, 'error');
  8916. }
  8917. }