app.js 326 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742
  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. };
  47. const API_BASE = '/api';
  48. function escapeHtml(str) {
  49. if (str === null || str === undefined) return '';
  50. return String(str)
  51. .replace(/&/g, '&')
  52. .replace(/</g, '&lt;')
  53. .replace(/>/g, '&gt;')
  54. .replace(/"/g, '&quot;')
  55. .replace(/'/g, '&#039;');
  56. }
  57. // Initialize on page load
  58. document.addEventListener('DOMContentLoaded', () => {
  59. const hash = window.location.hash.replace('#', '') || 'dashboard';
  60. navigate(hash);
  61. fetchData();
  62. // Live polling every 2.5 seconds
  63. setInterval(() => {
  64. if (state.isPolling) {
  65. fetchData(false);
  66. }
  67. }, 2500);
  68. });
  69. // Navigation Handler
  70. function navigate(tabName) {
  71. if (tabName === 'dynamic-routing' || tabName === 'routing') {
  72. navigate('bgp');
  73. return;
  74. }
  75. if (tabName === 'vlans') {
  76. navigate('interfaces');
  77. return;
  78. }
  79. state.activeTab = tabName;
  80. window.location.hash = tabName;
  81. // Update nav links styling
  82. document.querySelectorAll('.nav-link').forEach(link => {
  83. 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';
  84. });
  85. const activeNav = document.getElementById(`nav-${tabName}`);
  86. if (activeNav) {
  87. 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';
  88. }
  89. // Update page headers
  90. const titles = {
  91. dashboard: { title: 'Dashboard Overview', sub: 'Live router performance and network telemetry' },
  92. interfaces: { title: 'Network Interfaces', sub: 'Hierarchical view of physical interfaces and nested 802.1Q VLANs' },
  93. bridge: { title: 'Bridge Interfaces', sub: 'MikroTik-style IEEE 802.1D / 802.1Q VLAN Filtering Bridge with RSTP & FDB' },
  94. vlans: { title: 'VLAN Virtual Networks', sub: 'IEEE 802.1Q sub-interface segmentation and routing' },
  95. firewall: { title: 'MikroTik Firewall', sub: 'Filter rules, NAT, Mangle, Address Lists & Active Connections tracking' },
  96. routes: { title: 'Routing & Policy', sub: 'Routing tables, static routes (DAS/DAC), and policy routing rules' },
  97. bgp: { title: 'BGP Routing (/routing bgp)', sub: 'FRRouting BGP peering sessions, advertised networks, and BGP routing table (RIB)' },
  98. ospf: { title: 'OSPF Routing (/routing ospf)', sub: 'FRRouting OSPFv2 link-state routing, dynamic neighbor adjacencies, and multi-area topology' },
  99. 'routing-filters': { title: 'Routing Filters (/routing filter)', sub: 'MikroTik-style route filter chains, prefix matching, BGP attributes & policy maps' },
  100. 'dynamic-routing': { title: 'BGP Routing (/routing bgp)', sub: 'FRRouting dynamic routing' },
  101. ppp: { title: 'PPP Servers & Secrets', sub: 'MikroTik RouterOS user accounts, IP pools and VPN server concentrators' },
  102. eoip: { title: 'EoIP Tunnels', sub: 'Ethernet over IP Layer 2 tunneling (MikroTik RouterOS style)' },
  103. pppoe: { title: 'PPPoE Client WAN', sub: 'Point-to-Point Protocol over Ethernet WAN access' },
  104. wireguard: { title: 'WireGuard Kernel VPN', sub: 'Modern ultra-fast cryptographic VPN tunnel manager' },
  105. ipsec: { title: 'IPSec (IKEv2) strongSwan', sub: 'Enterprise Site-to-Site & Roadwarrior IPSec controller' },
  106. l2tp: { title: 'L2TP VPN Client', sub: 'Layer 2 Tunneling Protocol via xl2tpd' },
  107. pptp: { title: 'PPTP VPN Client', sub: 'Point-to-Point Tunneling Protocol with MPPE-128 encryption' },
  108. tools: { title: 'Troubleshoot & Diagnostic Tools (/tool)', sub: 'RouterOS-style Ping, Traceroute, MTR Telemetry, DNS resolution, and TCP Port probing' },
  109. persistence: { title: 'Debian Configuration', sub: 'Native /etc/network/interfaces.d/ persistence manager' }
  110. };
  111. const header = titles[tabName] || titles.dashboard;
  112. const pTitle = document.getElementById('page-title');
  113. if (pTitle) pTitle.innerText = header.title;
  114. const pSub = document.getElementById('page-subtitle');
  115. if (pSub) pSub.innerText = header.sub;
  116. // Toggle sections dynamically for all section elements
  117. document.querySelectorAll('main section[id^="section-"]').forEach(el => {
  118. if (el.id === `section-${tabName}`) {
  119. el.classList.remove('hidden');
  120. } else {
  121. el.classList.add('hidden');
  122. }
  123. });
  124. if (tabName === 'bridge') loadBridge();
  125. if (tabName === 'firewall') loadFirewall();
  126. if (tabName === 'routes') loadRoutes();
  127. if (tabName === 'bgp') {
  128. loadDynamicRouting();
  129. switchBgpSubTab(state.activeBgpSubTab || 'bgp-peers');
  130. }
  131. if (tabName === 'ospf') {
  132. loadDynamicRouting();
  133. switchOspfSubTab(state.activeOspfSubTab || 'ospf-ifaces');
  134. }
  135. if (tabName === 'routing-filters') loadDynamicRouting();
  136. if (tabName === 'dynamic-routing') loadDynamicRouting();
  137. if (tabName === 'ppp') loadPPP();
  138. if (tabName === 'eoip') loadEoIP();
  139. if (tabName === 'persistence') loadDebianConfig();
  140. if (tabName === 'pppoe') loadPPPoE();
  141. if (tabName === 'wireguard') loadWireGuard();
  142. if (tabName === 'ipsec') loadIPSec();
  143. if (tabName === 'l2tp') loadL2TP();
  144. if (tabName === 'pptp') loadPPTP();
  145. if (tabName === 'tools') loadToolsView();
  146. }
  147. // Fetch all core system, network and VPN telemetry
  148. async function fetchData(isManual = false) {
  149. const spinner = document.getElementById('refresh-spinner');
  150. if (isManual && spinner) spinner.classList.add('animate-spin');
  151. try {
  152. const [statusRes, ifacesRes, vlansRes, vpnRes, fwRes, dynRes, brSummaryRes] = await Promise.all([
  153. fetch(`${API_BASE}/system/status`),
  154. fetch(`${API_BASE}/interfaces`),
  155. fetch(`${API_BASE}/vlans`),
  156. fetch(`${API_BASE}/vpn/status`),
  157. fetch(`${API_BASE}/firewall/summary`),
  158. fetch(`${API_BASE}/routing/dynamic/summary`),
  159. fetch(`${API_BASE}/bridge/summary`)
  160. ]);
  161. if (brSummaryRes.ok) {
  162. state.bridgeSummary = await brSummaryRes.json();
  163. const bBridge = document.getElementById('badge-bridge-count');
  164. if (bBridge) bBridge.innerText = state.bridgeSummary?.bridges_count || 0;
  165. const sBr = document.getElementById('bridge-stat-bridges');
  166. if (sBr) sBr.innerText = state.bridgeSummary?.bridges_count || 0;
  167. const sPorts = document.getElementById('bridge-stat-ports');
  168. if (sPorts) sPorts.innerText = state.bridgeSummary?.ports_count || 0;
  169. const sHosts = document.getElementById('bridge-stat-hosts');
  170. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  171. }
  172. if (statusRes.ok) state.systemStatus = await statusRes.json();
  173. if (ifacesRes.ok) {
  174. const ifacesData = await ifacesRes.json();
  175. const rawIfaces = Array.isArray(ifacesData) ? ifacesData : [];
  176. state.interfaces = rawIfaces.filter(i => {
  177. if (!i.name) return false;
  178. if (i.name.startsWith('ep_')) return false;
  179. return !['gre0', 'gretap0', 'erspan0', 'sit0', 'tunl0', 'ip6tnl0', 'ip6gre0', 'ip6erspan0'].includes(i.name);
  180. });
  181. try { populateToolsInterfaces(); } catch (e) {}
  182. }
  183. if (vlansRes.ok) {
  184. const vlansData = await vlansRes.json();
  185. state.vlans = Array.isArray(vlansData) ? vlansData : [];
  186. }
  187. if (vpnRes.ok) state.vpnStatus = await vpnRes.json();
  188. if (fwRes && fwRes.ok) state.fwSummary = await fwRes.json();
  189. if (dynRes && dynRes.ok) state.dynSummary = await dynRes.json();
  190. updateSystemMetrics();
  191. updateBadges();
  192. if (state.activeTab === 'dashboard') renderDashboard();
  193. if (state.activeTab === 'interfaces') renderInterfacesList();
  194. if (state.activeTab === 'vlans') renderVlansList();
  195. if (state.activeTab === 'firewall') loadFirewall(false);
  196. if (state.activeTab === 'routes') loadRoutes(false);
  197. if (state.activeTab === 'dynamic-routing' || state.activeTab === 'bgp' || state.activeTab === 'ospf') loadDynamicRouting(false);
  198. if (state.activeTab === 'ppp') loadPPP(false);
  199. if (state.activeTab === 'eoip') loadEoIP(false);
  200. if (state.activeTab === 'pppoe') loadPPPoE(false);
  201. if (state.activeTab === 'wireguard') loadWireGuard(false);
  202. if (state.activeTab === 'ipsec') loadIPSec(false);
  203. if (state.activeTab === 'l2tp') loadL2TP(false);
  204. if (state.activeTab === 'pptp') loadPPTP(false);
  205. } catch (err) {
  206. console.error('Failed to fetch router state:', err);
  207. } finally {
  208. if (isManual && spinner) {
  209. setTimeout(() => spinner.classList.remove('animate-spin'), 300);
  210. }
  211. }
  212. }
  213. // Update Top KPI and Sidebar Telemetry
  214. function updateSystemMetrics() {
  215. const s = state.systemStatus;
  216. const v = state.vpnStatus;
  217. if (!s) return;
  218. // Sidebar
  219. document.getElementById('side-hostname').innerText = s.hostname || 'debian-lxc';
  220. document.getElementById('side-uptime').innerText = s.uptime_human || '0m';
  221. document.getElementById('side-gateway-ip').innerText = s.default_gateway ? `GW: ${s.default_gateway}` : 'GW: Isolated';
  222. if (s.cpu_pct !== undefined) {
  223. const pct = s.cpu_pct;
  224. document.getElementById('side-cpu-val').innerText = `${pct.toFixed(1)}%`;
  225. document.getElementById('side-cpu-bar').style.width = `${Math.max(4, Math.min(100, pct))}%`;
  226. const loadStr = s.cpu_load ? s.cpu_load.join(', ') : '-';
  227. document.getElementById('side-cpu-bar').title = `Container: ${pct}% | Host Loadavg: ${loadStr} (${s.cpu_cores || 1} cores)`;
  228. } else if (s.cpu_load && s.cpu_load.length > 0) {
  229. const cores = s.cpu_cores || 4;
  230. const pct = Math.min(100, Math.round((parseFloat(s.cpu_load[0]) / cores) * 100));
  231. document.getElementById('side-cpu-val').innerText = `${pct}%`;
  232. document.getElementById('side-cpu-bar').style.width = `${Math.max(4, pct)}%`;
  233. }
  234. document.getElementById('side-ram-val').innerText = `${Math.round(s.mem_usage_pct || 0)}%`;
  235. document.getElementById('side-ram-bar').style.width = `${Math.max(5, Math.round(s.mem_usage_pct || 0))}%`;
  236. // Dashboard Stats
  237. document.getElementById('stat-ifaces-up').innerText = s.up_ifaces || 0;
  238. document.getElementById('stat-ifaces-total').innerText = `${s.total_ifaces || 0} Total`;
  239. document.getElementById('stat-ifaces-down').innerText = `${s.down_ifaces || 0} DOWN`;
  240. document.getElementById('stat-vlans-count').innerText = s.vlan_ifaces || 0;
  241. // VPN Status Indicators
  242. if (v) {
  243. const totalActive = v.total_active_tunnels || 0;
  244. const statVpnActive = document.getElementById('stat-vpn-active');
  245. if (statVpnActive) statVpnActive.innerText = totalActive;
  246. const tunnelsDot = document.getElementById('tunnels-dot');
  247. const tunnelsLabel = document.getElementById('tunnels-label');
  248. if (tunnelsDot && tunnelsLabel) {
  249. if (totalActive > 0) {
  250. tunnelsDot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  251. tunnelsLabel.innerText = `${totalActive} Active VPN Tunnel${totalActive > 1 ? 's' : ''}`;
  252. } else {
  253. tunnelsDot.className = 'w-2 h-2 rounded-full bg-slate-500';
  254. tunnelsLabel.innerText = '0 Active VPN Tunnels';
  255. }
  256. }
  257. setDotBadge('badge-pppoe-status', (v.active_pppoe || 0) > 0 || v.pppoe_connected);
  258. setDotBadge('badge-wg-status', (v.active_wireguard || 0) > 0 || v.wireguard_active);
  259. setDotBadge('badge-ipsec-status', (v.active_ipsec || 0) > 0 || v.ipsec_active);
  260. setDotBadge('badge-l2tp-status', (v.active_l2tp || 0) > 0 || v.l2tp_connected);
  261. setDotBadge('badge-pptp-status', (v.active_pptp || 0) > 0 || v.pptp_connected);
  262. }
  263. // Total Live Bandwidth Rate
  264. let totalRx = 0;
  265. let totalTx = 0;
  266. (state.interfaces || []).forEach(i => {
  267. if (i.rate) {
  268. totalRx += i.rate.rx_bytes_sec || 0;
  269. totalTx += i.rate.tx_bytes_sec || 0;
  270. }
  271. });
  272. document.getElementById('stat-traffic-rx').innerText = formatTraffic(totalRx);
  273. document.getElementById('stat-traffic-tx').innerText = formatTraffic(totalTx);
  274. }
  275. function setDotBadge(id, active) {
  276. const el = document.getElementById(id);
  277. if (!el) return;
  278. if (active) {
  279. el.className = 'w-2 h-2 rounded-full bg-emerald-400 shadow-sm shadow-emerald-400/80';
  280. } else {
  281. el.className = 'w-2 h-2 rounded-full bg-slate-600';
  282. }
  283. }
  284. function updateBadges() {
  285. const bIfaces = document.getElementById('badge-ifaces-count');
  286. if (bIfaces) bIfaces.innerText = (state.interfaces || []).length;
  287. const bVlans = document.getElementById('badge-vlans-count');
  288. if (bVlans) bVlans.innerText = (state.vlans || []).length;
  289. if (state.fwSummary) {
  290. const totalFwRules = (state.fwSummary.filter_rules_count || 0) + (state.fwSummary.nat_rules_count || 0) + (state.fwSummary.mangle_rules_count || 0);
  291. const badgeFw = document.getElementById('badge-firewall-count');
  292. if (badgeFw) badgeFw.innerText = totalFwRules;
  293. }
  294. if (state.vpnStatus) {
  295. const v = state.vpnStatus;
  296. const bEoIP = document.getElementById('badge-eoip-count');
  297. if (bEoIP) bEoIP.innerText = v.total_eoip || 0;
  298. const bPPPSess = document.getElementById('badge-ppp-sessions');
  299. if (bPPPSess) bPPPSess.innerText = v.total_ppp_sessions || 0;
  300. setDotBadge('badge-pppoe-status', v.active_pppoe > 0 || v.pppoe_server_running);
  301. setDotBadge('badge-wg-status', v.active_wireguard > 0);
  302. setDotBadge('badge-ipsec-status', v.active_ipsec > 0 || v.ipsec_server_running);
  303. setDotBadge('badge-l2tp-status', v.active_l2tp > 0 || v.l2tp_server_running);
  304. setDotBadge('badge-pptp-status', v.active_pptp > 0 || v.pptp_server_running);
  305. }
  306. if (state.dynSummary) {
  307. const d = state.dynSummary;
  308. setDotBadge('badge-bgp-dot', d.bgp_running);
  309. setDotBadge('badge-ospf-dot', d.ospf_running);
  310. const bBgp = document.getElementById('badge-bgp-count');
  311. if (bBgp) bBgp.innerText = (state.bgpPeers || []).length;
  312. const bOspf = document.getElementById('badge-ospf-count');
  313. if (bOspf) bOspf.innerText = (state.ospfInterfaces || []).length;
  314. const bFilters = document.getElementById('badge-filters-count');
  315. if (bFilters) bFilters.innerText = (state.routingFilters || []).length;
  316. }
  317. }
  318. // Render Dashboard View
  319. function renderDashboard() {
  320. const matrix = document.getElementById('port-matrix');
  321. matrix.innerHTML = '';
  322. (state.interfaces || []).forEach(iface => {
  323. const isUp = iface.state === 'UP';
  324. const isVlan = iface.is_vlan;
  325. const portCard = document.createElement('div');
  326. portCard.className = `p-3 rounded-xl border transition-all cursor-pointer select-none group ${
  327. isUp
  328. ? (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')
  329. : 'bg-slate-900/40 border-slate-800/60 opacity-60 hover:opacity-100 hover:border-slate-700'
  330. }`;
  331. portCard.onclick = () => openIfaceModal(iface.name);
  332. let statusPillClass = isUp ? 'bg-emerald-500 shadow-sm shadow-emerald-500/50' : 'bg-rose-500';
  333. if (isVlan) statusPillClass = isUp ? 'bg-cyan-400 shadow-sm shadow-cyan-400/50' : 'bg-rose-500';
  334. portCard.innerHTML = `
  335. <div class="flex items-center justify-between mb-2">
  336. <span class="font-bold text-xs font-mono text-white group-hover:text-brand-400 transition truncate">${iface.name}</span>
  337. <span class="w-2 h-2 rounded-full ${statusPillClass}"></span>
  338. </div>
  339. <div class="text-[11px] font-mono text-slate-300 truncate">${iface.ipv4 && iface.ipv4.length > 0 ? iface.ipv4[0] : (iface.mac || 'No IP')}</div>
  340. <div class="mt-2 flex items-center justify-between text-[10px] text-slate-400">
  341. <span class="uppercase tracking-wider font-semibold">${isVlan ? `VLAN ${iface.vlan_id}` : iface.type}</span>
  342. <span>${iface.rate?.rx_human || '0 B/s'}</span>
  343. </div>
  344. `;
  345. matrix.appendChild(portCard);
  346. });
  347. const ifaceTbody = document.getElementById('quick-interfaces-table');
  348. ifaceTbody.innerHTML = '';
  349. (state.interfaces || []).slice(0, 6).forEach(i => {
  350. const isUp = i.state === 'UP';
  351. const tr = document.createElement('tr');
  352. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  353. tr.onclick = () => openIfaceModal(i.name);
  354. tr.innerHTML = `
  355. <td class="py-2.5 font-bold text-white flex items-center gap-2">
  356. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  357. <span>${i.name}</span>
  358. </td>
  359. <td class="py-2.5 text-slate-300 font-sans"><span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300">${i.role || 'LAN'}</span></td>
  360. <td class="py-2.5 text-slate-300">${i.ipv4 && i.ipv4.length > 0 ? i.ipv4[0] : '<span class="text-slate-600">-</span>'}</td>
  361. <td class="py-2.5 text-right font-sans font-semibold ${isUp ? 'text-emerald-400' : 'text-rose-400'}">${i.state}</td>
  362. `;
  363. ifaceTbody.appendChild(tr);
  364. });
  365. const vlanTbody = document.getElementById('quick-vlans-table');
  366. vlanTbody.innerHTML = '';
  367. const vlans = state.vlans || [];
  368. if (vlans.length === 0) {
  369. vlanTbody.innerHTML = `<tr><td colspan="4" class="py-4 text-center text-slate-500 font-sans">No VLANs configured. Click "+ Add" above to create one.</td></tr>`;
  370. } else {
  371. vlans.slice(0, 6).forEach(v => {
  372. const tr = document.createElement('tr');
  373. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  374. tr.onclick = () => openIfaceModal(v.name);
  375. tr.innerHTML = `
  376. <td class="py-2.5"><span class="px-2 py-0.5 rounded text-[11px] bg-cyan-950 text-cyan-400 border border-cyan-800 font-bold">VLAN ${v.vlan_id}</span></td>
  377. <td class="py-2.5 text-white font-bold">${v.name}</td>
  378. <td class="py-2.5 text-slate-300">${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600">Unnumbered</span>'}</td>
  379. <td class="py-2.5 text-right text-slate-400">${v.parent_name || 'eth0'}</td>
  380. `;
  381. vlanTbody.appendChild(tr);
  382. });
  383. }
  384. }
  385. // Expand / Collapse Handlers
  386. function toggleExpand(parentName) {
  387. if (state.expandedParents.has(parentName)) {
  388. state.expandedParents.delete(parentName);
  389. } else {
  390. state.expandedParents.add(parentName);
  391. }
  392. renderInterfacesList();
  393. }
  394. function expandAllIfaces(expand) {
  395. if (expand) {
  396. (state.interfaces || []).forEach(i => {
  397. if (!i.is_vlan) state.expandedParents.add(i.name);
  398. });
  399. } else {
  400. state.expandedParents.clear();
  401. }
  402. renderInterfacesList();
  403. }
  404. // Filter and Render Hierarchical Interfaces List
  405. function filterIfaces(filter) {
  406. state.ifaceFilter = filter;
  407. document.querySelectorAll('.filter-btn').forEach(btn => {
  408. btn.className = 'filter-btn px-3 py-1.5 rounded-lg text-xs font-medium text-slate-400 hover:bg-slate-800 hover:text-white';
  409. });
  410. const activeBtn = document.getElementById(`filter-${filter}`);
  411. if (activeBtn) {
  412. activeBtn.className = 'filter-btn px-3 py-1.5 rounded-lg text-xs font-medium bg-slate-800 text-white border border-slate-700';
  413. }
  414. renderInterfacesList();
  415. }
  416. function renderInterfacesList() {
  417. const tbody = document.getElementById('interfaces-tree-tbody');
  418. const emptyState = document.getElementById('interfaces-empty-state');
  419. const summary = document.getElementById('ifaces-list-summary');
  420. const query = (document.getElementById('iface-search')?.value || '').toLowerCase();
  421. tbody.innerHTML = '';
  422. const allIfaces = state.interfaces || [];
  423. const allVlans = state.vlans || [];
  424. const parentIfaces = allIfaces.filter(i => !i.is_vlan);
  425. const filteredParents = parentIfaces.filter(parent => {
  426. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  427. if (query) {
  428. const matchParent = parent.name.toLowerCase().includes(query) || (parent.role || '').toLowerCase().includes(query);
  429. const matchVlan = childVlans.some(v => v.name.toLowerCase().includes(query) || String(v.vlan_id).includes(query) || (v.description || '').toLowerCase().includes(query));
  430. if (!matchParent && !matchVlan) return false;
  431. }
  432. if (state.ifaceFilter === 'has_vlans') return childVlans.length > 0;
  433. if (state.ifaceFilter === 'physical') return parent.type !== 'loopback';
  434. if (state.ifaceFilter === 'up') return parent.state === 'UP';
  435. return true;
  436. });
  437. if (summary) {
  438. summary.innerText = `${parentIfaces.length} Physical/Parent Links • ${allVlans.length} Active VLANs`;
  439. }
  440. if (filteredParents.length === 0) {
  441. emptyState?.classList.remove('hidden');
  442. return;
  443. }
  444. emptyState?.classList.add('hidden');
  445. filteredParents.forEach(parent => {
  446. const isUp = parent.state === 'UP';
  447. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  448. const isExpanded = state.expandedParents.has(parent.name);
  449. const parentRow = document.createElement('tr');
  450. parentRow.className = `hover:bg-slate-800/50 transition border-b border-slate-800/80 ${isExpanded ? 'bg-slate-900/80' : ''}`;
  451. parentRow.innerHTML = `
  452. <td class="py-3 px-3 text-center">
  453. <button onclick="toggleExpand('${parent.name}')" title="${isExpanded ? 'Collapse VLANs' : 'Expand VLANs'}"
  454. class="w-6 h-6 rounded flex items-center justify-center hover:bg-slate-800 text-slate-400 hover:text-white transition">
  455. <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">
  456. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M9 5l7 7-7 7" />
  457. </svg>
  458. </button>
  459. </td>
  460. <td class="py-3 px-4">
  461. <div class="flex items-center space-x-2.5">
  462. <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">
  463. ${parent.type === 'loopback' ? 'LO' : 'NIC'}
  464. </div>
  465. <div>
  466. <div class="flex items-center gap-2">
  467. <span class="font-bold text-white text-sm cursor-pointer hover:text-cyan-400" onclick="toggleExpand('${parent.name}')">${parent.name}</span>
  468. ${childVlans.length > 0
  469. ? `<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>`
  470. : `<span onclick="toggleExpand('${parent.name}')" class="cursor-pointer text-[10px] bg-slate-800/60 text-slate-500 px-1.5 py-0.5 rounded font-mono hover:text-slate-300">0 VLANs</span>`
  471. }
  472. </div>
  473. <div class="text-[10px] text-slate-500 font-sans mt-0.5">${parent.type}</div>
  474. </div>
  475. </div>
  476. </td>
  477. <td class="py-3 px-4 font-sans">
  478. <div class="flex items-center gap-1.5">
  479. <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>
  480. <span class="text-xs text-slate-400 truncate max-w-[120px]">${parent.description || '-'}</span>
  481. </div>
  482. </td>
  483. <td class="py-3 px-4">
  484. ${parent.ipv4 && parent.ipv4.length > 0
  485. ? `<div class="text-white font-medium">${parent.ipv4[0]}</div>`
  486. : '<span class="text-slate-600 font-sans">Unassigned</span>'
  487. }
  488. </td>
  489. <td class="py-3 px-4 text-slate-400 text-[11px]">
  490. <div>${parent.mac || 'N/A'}</div>
  491. <div class="text-[10px] text-slate-500">MTU ${parent.mtu}</div>
  492. </td>
  493. <td class="py-3 px-4 text-[11px]">
  494. <div class="flex items-center space-x-2">
  495. <span class="text-emerald-400">↓ ${parent.rate?.rx_human || '0 B/s'}</span>
  496. <span class="text-cyan-400">↑ ${parent.rate?.tx_human || '0 B/s'}</span>
  497. </div>
  498. </td>
  499. <td class="py-3 px-4 font-sans">
  500. <button onclick="toggleInterfaceState('${parent.name}', '${isUp ? 'down' : 'up'}')"
  501. class="flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full transition ${
  502. 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'
  503. }" title="Click to toggle link status">
  504. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  505. <span>${parent.state}</span>
  506. </button>
  507. </td>
  508. <td class="py-3 px-4 text-right space-x-2 font-sans">
  509. <button onclick="openVlanModal('${parent.name}')"
  510. 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">
  511. + Add VLAN
  512. </button>
  513. <button onclick="openIfaceModal('${parent.name}')"
  514. 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">
  515. Configure
  516. </button>
  517. </td>
  518. `;
  519. tbody.appendChild(parentRow);
  520. if (isExpanded) {
  521. const drawerRow = document.createElement('tr');
  522. drawerRow.className = 'bg-slate-950/80 border-b border-slate-800/90';
  523. const drawerCell = document.createElement('td');
  524. drawerCell.colSpan = 8;
  525. drawerCell.className = 'p-0';
  526. drawerCell.innerHTML = `
  527. <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">
  528. <div class="flex items-center justify-between mb-3">
  529. <div class="flex items-center space-x-3">
  530. <span class="font-bold text-xs text-white uppercase tracking-wider flex items-center gap-1.5 font-sans">
  531. <span>VLAN Sub-interfaces on <code class="text-cyan-300 lowercase">${parent.name}</code></span>
  532. </span>
  533. <span class="text-[11px] bg-cyan-950 text-cyan-400 px-2 py-0.5 rounded-full border border-cyan-800/60 font-mono">
  534. ${childVlans.length} Attached
  535. </span>
  536. </div>
  537. <button onclick="openVlanModal('${parent.name}')"
  538. 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">
  539. <span>+ Create VLAN on ${parent.name}</span>
  540. </button>
  541. </div>
  542. ${childVlans.length === 0 ? `
  543. <div class="p-6 text-center border border-dashed border-slate-800 rounded-xl bg-slate-900/40 font-sans">
  544. <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>
  545. <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">
  546. <span>+ Create Your First VLAN on ${parent.name}</span>
  547. </button>
  548. </div>
  549. ` : `
  550. <div class="overflow-x-auto rounded-lg border border-slate-800 bg-slate-900/90 shadow-inner">
  551. <table class="w-full text-left text-xs font-mono">
  552. <thead class="text-slate-400 bg-slate-950/70 border-b border-slate-800 uppercase tracking-wider text-[10px] font-sans">
  553. <tr>
  554. <th class="py-2.5 px-4">VLAN ID</th>
  555. <th class="py-2.5 px-4">Interface Device</th>
  556. <th class="py-2.5 px-4">Subnet Gateway</th>
  557. <th class="py-2.5 px-4">Role / Alias</th>
  558. <th class="py-2.5 px-4">MTU</th>
  559. <th class="py-2.5 px-4">Throughput</th>
  560. <th class="py-2.5 px-4">Status</th>
  561. <th class="py-2.5 px-4 text-right">Actions</th>
  562. </tr>
  563. </thead>
  564. <tbody class="divide-y divide-slate-800/70">
  565. ${childVlans.map(v => {
  566. const isVlanUp = v.state === 'UP';
  567. return `
  568. <tr class="hover:bg-slate-800/40 transition">
  569. <td class="py-2.5 px-4">
  570. <span class="px-2 py-0.5 rounded text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800 shadow-sm">
  571. VLAN ${v.vlan_id}
  572. </span>
  573. </td>
  574. <td class="py-2.5 px-4 font-bold text-white flex items-center gap-1.5">
  575. <span class="text-cyan-500">└─</span>
  576. <span>${v.name}</span>
  577. </td>
  578. <td class="py-2.5 px-4 text-emerald-400 font-medium">
  579. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  580. </td>
  581. <td class="py-2.5 px-4 font-sans text-slate-300">
  582. <span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 mr-1.5">${v.role || 'VLAN'}</span>
  583. <span class="text-slate-400 text-xs">${v.description || '-'}</span>
  584. </td>
  585. <td class="py-2.5 px-4 text-slate-400">${v.mtu}</td>
  586. <td class="py-2.5 px-4 text-[11px]">
  587. <span class="text-emerald-400">↓ ${v.rate?.rx_human || '0 B/s'}</span>
  588. <span class="text-cyan-400 ml-1.5">↑ ${v.rate?.tx_human || '0 B/s'}</span>
  589. </td>
  590. <td class="py-2.5 px-4 font-sans">
  591. <button onclick="toggleInterfaceState('${v.name}', '${isVlanUp ? 'down' : 'up'}')"
  592. class="flex items-center gap-1 text-[11px] font-semibold px-2 py-0.5 rounded-full ${
  593. 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'
  594. }">
  595. <span class="w-1.5 h-1.5 rounded-full ${isVlanUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  596. <span>${v.state}</span>
  597. </button>
  598. </td>
  599. <td class="py-2.5 px-4 text-right space-x-1.5 font-sans">
  600. <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>
  601. <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>
  602. </td>
  603. </tr>
  604. `;
  605. }).join('')}
  606. </tbody>
  607. </table>
  608. </div>
  609. `}
  610. </div>
  611. `;
  612. drawerRow.appendChild(drawerCell);
  613. tbody.appendChild(drawerRow);
  614. }
  615. });
  616. }
  617. // Render VLANs Dedicated View
  618. function renderVlansList() {
  619. const tbody = document.getElementById('vlans-table-body');
  620. if (!tbody) return;
  621. const emptyState = document.getElementById('vlans-empty-state');
  622. const countBadge = document.getElementById('vlans-table-count');
  623. const query = (document.getElementById('vlan-search')?.value || '').toLowerCase();
  624. tbody.innerHTML = '';
  625. const allVlans = state.vlans || [];
  626. if (countBadge) countBadge.innerText = allVlans.length;
  627. const filtered = allVlans.filter(v => {
  628. if (!query) return true;
  629. return v.name.toLowerCase().includes(query) ||
  630. String(v.vlan_id).includes(query) ||
  631. (v.description || '').toLowerCase().includes(query) ||
  632. (v.ipv4 && v.ipv4.some(ip => ip.includes(query)));
  633. });
  634. if (allVlans.length === 0) {
  635. emptyState.classList.remove('hidden');
  636. return;
  637. }
  638. emptyState.classList.add('hidden');
  639. filtered.forEach(v => {
  640. const isUp = v.state === 'UP';
  641. const tr = document.createElement('tr');
  642. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  643. tr.innerHTML = `
  644. <td class="py-3 px-4">
  645. <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">
  646. VLAN ${v.vlan_id}
  647. </span>
  648. </td>
  649. <td class="py-3 px-4 font-bold text-white">${v.name}</td>
  650. <td class="py-3 px-4 text-slate-300">
  651. <span class="bg-slate-800 text-slate-200 px-2 py-0.5 rounded text-[11px]">${v.parent_name || 'eth0'}</span>
  652. </td>
  653. <td class="py-3 px-4 text-emerald-400 font-medium">
  654. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  655. </td>
  656. <td class="py-3 px-4 text-slate-300 font-sans">
  657. <span class="text-slate-400 text-xs">${v.description || v.role || '-'}</span>
  658. </td>
  659. <td class="py-3 px-4 text-slate-400">${v.mtu}</td>
  660. <td class="py-3 px-4 font-sans">
  661. <button onclick="toggleInterfaceState('${v.name}', '${isUp ? 'down' : 'up'}')"
  662. class="flex items-center gap-1.5 text-xs font-semibold px-2 py-0.5 rounded-full ${
  663. 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'
  664. }">
  665. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  666. <span>${v.state}</span>
  667. </button>
  668. </td>
  669. <td class="py-3 px-4 text-right space-x-2 font-sans">
  670. <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>
  671. <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>
  672. </td>
  673. `;
  674. tbody.appendChild(tr);
  675. });
  676. }
  677. // Toggle interface UP / DOWN
  678. async function toggleInterfaceState(name, newState) {
  679. try {
  680. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(name)}/state`, {
  681. method: 'POST',
  682. headers: { 'Content-Type': 'application/json' },
  683. body: JSON.stringify({ state: newState })
  684. });
  685. const data = await res.json();
  686. if (res.ok) {
  687. showToast('Interface Updated', `Interface ${name} is now ${newState.toUpperCase()}`, 'success');
  688. fetchData(false);
  689. } else {
  690. showToast('Error', data.message || 'Failed to toggle interface state', 'error');
  691. }
  692. } catch (err) {
  693. showToast('Error', err.message, 'error');
  694. }
  695. }
  696. // ---------------- MikroTik Flag & Utilities ----------------
  697. function renderMikroTikFlag(running, disabled) {
  698. if (running) {
  699. 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>`;
  700. }
  701. if (disabled) {
  702. 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>`;
  703. }
  704. 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>`;
  705. }
  706. function copyToClipboard(text, label = 'Text') {
  707. navigator.clipboard.writeText(text).then(() => {
  708. showToast('Copied', `${label} copied to clipboard`, 'success');
  709. }).catch(() => {
  710. prompt('Copy value:', text);
  711. });
  712. }
  713. // ======================== PPPoE Multi-Instance ========================
  714. async function loadPPPoE(populateInputs = true) {
  715. try {
  716. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`);
  717. const list = await res.json();
  718. state.pppoeList = Array.isArray(list) ? list : [];
  719. const badge = document.getElementById('pppoe-count-badge');
  720. if (badge) badge.innerText = `${state.pppoeList.length} Interface${state.pppoeList.length !== 1 ? 's' : ''}`;
  721. const tbody = document.getElementById('pppoe-table-body');
  722. const empty = document.getElementById('pppoe-empty');
  723. if (!tbody) return;
  724. tbody.innerHTML = '';
  725. if (state.pppoeList.length === 0) {
  726. if (empty) empty.classList.remove('hidden');
  727. } else {
  728. if (empty) empty.classList.add('hidden');
  729. state.pppoeList.forEach(inst => {
  730. const tr = document.createElement('tr');
  731. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  732. tr.innerHTML = `
  733. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  734. <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
  735. <td class="py-2.5 px-3 text-cyan-400 font-mono">${inst.interface}</td>
  736. <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
  737. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
  738. <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
  739. <td class="py-2.5 px-3 text-center">
  740. <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'}">
  741. ${inst.default_route ? 'Yes' : 'No'}
  742. </span>
  743. </td>
  744. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  745. ${inst.running ? `
  746. <button onclick="disconnectPPPoEInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  747. ` : `
  748. <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>
  749. `}
  750. <button onclick="togglePPPoEState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  751. ${inst.disabled ? 'Enable' : 'Disable'}
  752. </button>
  753. <button onclick="openEditPPPoEModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  754. <button onclick="deletePPPoEInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  755. </td>
  756. `;
  757. tbody.appendChild(tr);
  758. });
  759. }
  760. } catch (err) {
  761. console.error('Failed to load PPPoE:', err);
  762. }
  763. }
  764. function openAddPPPoEModal() {
  765. document.getElementById('pppoe-modal-title').innerText = 'Add PPPoE Client Interface';
  766. document.getElementById('pppoe-modal-edit-orig').value = '';
  767. document.getElementById('pppoe-modal-name').value = `pppoe-out${(state.pppoeList || []).length + 1}`;
  768. document.getElementById('pppoe-modal-name').readOnly = false;
  769. document.getElementById('pppoe-modal-user').value = '';
  770. document.getElementById('pppoe-modal-pass').value = '';
  771. document.getElementById('pppoe-modal-service').value = '';
  772. document.getElementById('pppoe-modal-mtu').value = '1492';
  773. document.getElementById('pppoe-modal-defroute').checked = true;
  774. document.getElementById('pppoe-modal-reconnect').checked = true;
  775. document.getElementById('pppoe-modal-disabled').checked = false;
  776. // Populate interfaces
  777. const sel = document.getElementById('pppoe-modal-iface');
  778. sel.innerHTML = '';
  779. (state.interfaces || []).forEach(i => {
  780. if (i.name === 'lo') return;
  781. const opt = document.createElement('option');
  782. opt.value = i.name;
  783. opt.innerText = `${i.name} (${i.role || i.type})`;
  784. sel.appendChild(opt);
  785. });
  786. document.getElementById('pppoe-modal').classList.remove('hidden');
  787. }
  788. function openEditPPPoEModal(name) {
  789. const inst = (state.pppoeList || []).find(i => i.name === name);
  790. if (!inst) return;
  791. document.getElementById('pppoe-modal-title').innerText = `Edit PPPoE Client: ${name}`;
  792. document.getElementById('pppoe-modal-edit-orig').value = name;
  793. document.getElementById('pppoe-modal-name').value = inst.name;
  794. document.getElementById('pppoe-modal-name').readOnly = true;
  795. document.getElementById('pppoe-modal-user').value = inst.username || '';
  796. document.getElementById('pppoe-modal-pass').value = inst.password || '';
  797. document.getElementById('pppoe-modal-service').value = inst.service_name || '';
  798. document.getElementById('pppoe-modal-mtu').value = inst.mtu || 1492;
  799. document.getElementById('pppoe-modal-defroute').checked = inst.default_route ?? true;
  800. document.getElementById('pppoe-modal-reconnect').checked = inst.auto_reconnect ?? true;
  801. document.getElementById('pppoe-modal-disabled').checked = !!inst.disabled;
  802. const sel = document.getElementById('pppoe-modal-iface');
  803. sel.innerHTML = '';
  804. (state.interfaces || []).forEach(i => {
  805. if (i.name === 'lo') return;
  806. const opt = document.createElement('option');
  807. opt.value = i.name;
  808. opt.innerText = `${i.name} (${i.role || i.type})`;
  809. if (i.name === inst.interface) opt.selected = true;
  810. sel.appendChild(opt);
  811. });
  812. document.getElementById('pppoe-modal').classList.remove('hidden');
  813. }
  814. function closePPPoEModal() {
  815. document.getElementById('pppoe-modal').classList.add('hidden');
  816. }
  817. async function submitSavePPPoE(e) {
  818. e.preventDefault();
  819. const name = document.getElementById('pppoe-modal-name').value.trim();
  820. const iface = document.getElementById('pppoe-modal-iface').value;
  821. const user = document.getElementById('pppoe-modal-user').value.trim();
  822. const pass = document.getElementById('pppoe-modal-pass').value;
  823. const service = document.getElementById('pppoe-modal-service').value.trim();
  824. const mtu = parseInt(document.getElementById('pppoe-modal-mtu').value, 10) || 1492;
  825. const defRoute = document.getElementById('pppoe-modal-defroute').checked;
  826. const reconnect = document.getElementById('pppoe-modal-reconnect').checked;
  827. const disabled = document.getElementById('pppoe-modal-disabled').checked;
  828. try {
  829. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`, {
  830. method: 'POST',
  831. headers: { 'Content-Type': 'application/json' },
  832. body: JSON.stringify({
  833. name,
  834. interface: iface,
  835. username: user,
  836. password: pass,
  837. service_name: service,
  838. mtu,
  839. default_route: defRoute,
  840. auto_reconnect: reconnect,
  841. disabled
  842. })
  843. });
  844. if (res.ok) {
  845. showToast('PPPoE Saved', `Configuration for ${name} saved`, 'success');
  846. closePPPoEModal();
  847. loadPPPoE(false);
  848. fetchData(false);
  849. } else {
  850. const err = await res.json();
  851. showToast('Error', err.message || 'Failed to save PPPoE', 'error');
  852. }
  853. } catch (err) {
  854. showToast('Error', err.message, 'error');
  855. }
  856. }
  857. async function connectPPPoEInstance(name) {
  858. try {
  859. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  860. if (res.ok) {
  861. showToast('Connecting', `Dialing ${name}...`, 'info');
  862. setTimeout(() => loadPPPoE(false), 2000);
  863. }
  864. } catch (err) {
  865. showToast('Error', err.message, 'error');
  866. }
  867. }
  868. async function disconnectPPPoEInstance(name) {
  869. try {
  870. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  871. if (res.ok) {
  872. showToast('Disconnected', `${name} session terminated`, 'info');
  873. setTimeout(() => loadPPPoE(false), 1000);
  874. }
  875. } catch (err) {
  876. showToast('Error', err.message, 'error');
  877. }
  878. }
  879. async function togglePPPoEState(name, enable) {
  880. try {
  881. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/state`, {
  882. method: 'POST',
  883. headers: { 'Content-Type': 'application/json' },
  884. body: JSON.stringify({ enabled: enable })
  885. });
  886. if (res.ok) {
  887. showToast(enable ? 'Enabled' : 'Disabled', `${name} is now ${enable ? 'enabled' : 'disabled'}`, 'info');
  888. loadPPPoE(false);
  889. }
  890. } catch (err) {
  891. showToast('Error', err.message, 'error');
  892. }
  893. }
  894. async function deletePPPoEInstance(name) {
  895. if (!confirm(`Are you sure you want to delete PPPoE client ${name}?`)) return;
  896. try {
  897. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  898. if (res.ok) {
  899. showToast('Deleted', `PPPoE client ${name} removed`, 'success');
  900. loadPPPoE(false);
  901. fetchData(false);
  902. }
  903. } catch (err) {
  904. showToast('Error', err.message, 'error');
  905. }
  906. }
  907. // ======================== WireGuard Multi-Interface & Multi-Peer ========================
  908. state.wgSubTab = 'ifaces';
  909. function switchWGSubTab(tab) {
  910. state.wgSubTab = tab;
  911. const ifacesPanel = document.getElementById('wg-subtab-ifaces');
  912. const peersPanel = document.getElementById('wg-subtab-peers');
  913. const ifacesBtn = document.getElementById('wg-subtab-btn-ifaces');
  914. const peersBtn = document.getElementById('wg-subtab-btn-peers');
  915. if (tab === 'ifaces') {
  916. ifacesPanel?.classList.remove('hidden');
  917. peersPanel?.classList.add('hidden');
  918. 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';
  919. 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';
  920. } else {
  921. ifacesPanel?.classList.add('hidden');
  922. peersPanel?.classList.remove('hidden');
  923. 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';
  924. 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';
  925. renderWGPeers();
  926. }
  927. }
  928. async function loadWireGuard(populateInputs = true) {
  929. try {
  930. const [ifacesRes, peersRes] = await Promise.all([
  931. fetch(`${API_BASE}/vpn/wireguard/interfaces`),
  932. fetch(`${API_BASE}/vpn/wireguard/peers`)
  933. ]);
  934. const ifaces = ifacesRes.ok ? await ifacesRes.json() : [];
  935. const peers = peersRes.ok ? await peersRes.json() : [];
  936. state.wgInterfaces = Array.isArray(ifaces) ? ifaces : [];
  937. state.wgPeers = Array.isArray(peers) ? peers : [];
  938. // Badges
  939. const ifacesCountBadge = document.getElementById('wg-ifaces-count');
  940. if (ifacesCountBadge) ifacesCountBadge.innerText = `${state.wgInterfaces.length} Interfaces`;
  941. const peersCountBadge = document.getElementById('wg-peers-count');
  942. if (peersCountBadge) peersCountBadge.innerText = `${state.wgPeers.length} Peers`;
  943. const subTabIfaces = document.getElementById('wg-subtab-badge-ifaces');
  944. if (subTabIfaces) subTabIfaces.innerText = state.wgInterfaces.length;
  945. const subTabPeers = document.getElementById('wg-subtab-badge-peers');
  946. if (subTabPeers) subTabPeers.innerText = state.wgPeers.length;
  947. // Render Interfaces
  948. const ifacesTbody = document.getElementById('wg-ifaces-table-body');
  949. const ifacesEmpty = document.getElementById('wg-ifaces-empty');
  950. if (ifacesTbody) {
  951. ifacesTbody.innerHTML = '';
  952. if (state.wgInterfaces.length === 0) {
  953. if (ifacesEmpty) ifacesEmpty.classList.remove('hidden');
  954. } else {
  955. if (ifacesEmpty) ifacesEmpty.classList.add('hidden');
  956. state.wgInterfaces.forEach(iface => {
  957. const peersOnIface = state.wgPeers.filter(p => p.interface === iface.name).length;
  958. const tr = document.createElement('tr');
  959. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  960. tr.innerHTML = `
  961. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(iface.running, iface.disabled)}</td>
  962. <td class="py-2.5 px-3 font-bold text-white">${iface.name}</td>
  963. <td class="py-2.5 px-3 text-amber-400 font-mono">${iface.listen_port}</td>
  964. <td class="py-2.5 px-3 text-emerald-400 font-mono">${iface.address || '-'}</td>
  965. <td class="py-2.5 px-3 text-slate-300 font-mono">
  966. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${iface.public_key}', 'Public Key')" title="Click to copy: ${iface.public_key}">
  967. ${(iface.public_key || '').substring(0, 10)}... 📋
  968. </span>
  969. </td>
  970. <td class="py-2.5 px-3 text-slate-400 font-mono">${iface.mtu || 1420}</td>
  971. <td class="py-2.5 px-3 text-center">
  972. <span class="px-2 py-0.5 rounded text-[10px] font-sans bg-slate-800 text-slate-300">${peersOnIface} peer${peersOnIface !== 1 ? 's' : ''}</span>
  973. </td>
  974. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  975. ${iface.running ? `
  976. <button onclick="stopWGInterface('${iface.name}')" class="text-xs text-rose-400 hover:text-rose-300">Stop</button>
  977. ` : `
  978. <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">Start</button>
  979. `}
  980. <button onclick="toggleWGInterfaceState('${iface.name}', ${iface.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  981. ${iface.disabled ? 'Enable' : 'Disable'}
  982. </button>
  983. <button onclick="openEditWGInterfaceModal('${iface.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  984. <button onclick="deleteWGInterface('${iface.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  985. </td>
  986. `;
  987. ifacesTbody.appendChild(tr);
  988. });
  989. }
  990. }
  991. // Populate filter dropdown in peers tab
  992. const filterSel = document.getElementById('wg-peers-filter-iface');
  993. if (filterSel) {
  994. const currentVal = filterSel.value;
  995. filterSel.innerHTML = '<option value="">All Interfaces</option>';
  996. state.wgInterfaces.forEach(i => {
  997. const opt = document.createElement('option');
  998. opt.value = i.name;
  999. opt.innerText = i.name;
  1000. if (i.name === currentVal) opt.selected = true;
  1001. filterSel.appendChild(opt);
  1002. });
  1003. }
  1004. renderWGPeers();
  1005. } catch (err) {
  1006. console.error('Failed to load WireGuard:', err);
  1007. }
  1008. }
  1009. function renderWGPeers() {
  1010. const filterSel = document.getElementById('wg-peers-filter-iface');
  1011. const selectedIface = filterSel ? filterSel.value : '';
  1012. const tbody = document.getElementById('wg-peers-table-body');
  1013. const empty = document.getElementById('wg-peers-empty');
  1014. if (!tbody) return;
  1015. tbody.innerHTML = '';
  1016. const filtered = selectedIface ? state.wgPeers.filter(p => p.interface === selectedIface) : state.wgPeers;
  1017. if (filtered.length === 0) {
  1018. if (empty) empty.classList.remove('hidden');
  1019. } else {
  1020. if (empty) empty.classList.add('hidden');
  1021. filtered.forEach(p => {
  1022. const isOnline = p.latest_handshake && !p.latest_handshake.includes('Never');
  1023. const tr = document.createElement('tr');
  1024. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1025. tr.innerHTML = `
  1026. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isOnline, p.disabled)}</td>
  1027. <td class="py-2.5 px-3 font-mono font-bold text-rose-400">${p.interface}</td>
  1028. <td class="py-2.5 px-3 font-bold text-white font-sans">${p.name || 'Unnamed'}</td>
  1029. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1030. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${p.public_key}', 'Peer Public Key')" title="${p.public_key}">
  1031. ${p.public_key.substring(0, 10)}... 📋
  1032. </span>
  1033. </td>
  1034. <td class="py-2.5 px-3 text-emerald-400 font-mono font-semibold">${(p.allowed_ips || []).join(', ')}</td>
  1035. <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>
  1036. <td class="py-2.5 px-3 text-slate-300 font-sans">${p.latest_handshake || 'Never'}</td>
  1037. <td class="py-2.5 px-3 font-mono text-[11px]">
  1038. <span class="text-emerald-400">↓ ${p.transfer_rx_human || '0 B'}</span>
  1039. <span class="text-cyan-400 ml-1">↑ ${p.transfer_tx_human || '0 B'}</span>
  1040. </td>
  1041. <td class="py-2.5 px-3 text-right font-sans space-x-2">
  1042. <button onclick="openWGClientConfModal('${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>
  1043. <button onclick="deleteWGPeer('${p.interface}', '${p.public_key}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  1044. </td>
  1045. `;
  1046. tbody.appendChild(tr);
  1047. });
  1048. }
  1049. }
  1050. function openAddWGInterfaceModal() {
  1051. document.getElementById('wg-iface-modal-title').innerText = 'Add WireGuard Interface';
  1052. document.getElementById('wg-iface-modal-edit-orig').value = '';
  1053. document.getElementById('wg-iface-modal-name').value = `wg${(state.wgInterfaces || []).length}`;
  1054. document.getElementById('wg-iface-modal-name').readOnly = false;
  1055. document.getElementById('wg-iface-modal-port').value = 51820 + (state.wgInterfaces || []).length;
  1056. document.getElementById('wg-iface-modal-addr').value = `10.${10 + (state.wgInterfaces || []).length}.0.1/24`;
  1057. document.getElementById('wg-iface-modal-mtu').value = '1420';
  1058. document.getElementById('wg-iface-modal-pubkey').value = '';
  1059. document.getElementById('wg-iface-modal-privkey').value = '';
  1060. document.getElementById('wg-iface-modal-disabled').checked = false;
  1061. generateWGInterfaceKeys();
  1062. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1063. }
  1064. function openEditWGInterfaceModal(name) {
  1065. const iface = (state.wgInterfaces || []).find(i => i.name === name);
  1066. if (!iface) return;
  1067. document.getElementById('wg-iface-modal-title').innerText = `Edit WireGuard Interface: ${name}`;
  1068. document.getElementById('wg-iface-modal-edit-orig').value = name;
  1069. document.getElementById('wg-iface-modal-name').value = iface.name;
  1070. document.getElementById('wg-iface-modal-name').readOnly = true;
  1071. document.getElementById('wg-iface-modal-port').value = iface.listen_port || 51820;
  1072. document.getElementById('wg-iface-modal-addr').value = iface.address || '';
  1073. document.getElementById('wg-iface-modal-mtu').value = iface.mtu || 1420;
  1074. document.getElementById('wg-iface-modal-pubkey').value = iface.public_key || '';
  1075. document.getElementById('wg-iface-modal-privkey').value = iface.private_key || '';
  1076. document.getElementById('wg-iface-modal-disabled').checked = !!iface.disabled;
  1077. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1078. }
  1079. function closeAddWGInterfaceModal() {
  1080. document.getElementById('wg-iface-modal').classList.add('hidden');
  1081. }
  1082. async function generateWGInterfaceKeys() {
  1083. try {
  1084. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1085. const keys = await res.json();
  1086. if (res.ok) {
  1087. document.getElementById('wg-iface-modal-privkey').value = keys.private_key;
  1088. document.getElementById('wg-iface-modal-pubkey').value = keys.public_key;
  1089. }
  1090. } catch (err) {
  1091. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1092. }
  1093. }
  1094. async function submitSaveWGInterface(e) {
  1095. e.preventDefault();
  1096. const name = document.getElementById('wg-iface-modal-name').value.trim();
  1097. const port = parseInt(document.getElementById('wg-iface-modal-port').value, 10) || 51820;
  1098. const addr = document.getElementById('wg-iface-modal-addr').value.trim();
  1099. const mtu = parseInt(document.getElementById('wg-iface-modal-mtu').value, 10) || 1420;
  1100. const pub = document.getElementById('wg-iface-modal-pubkey').value.trim();
  1101. const priv = document.getElementById('wg-iface-modal-privkey').value.trim();
  1102. const disabled = document.getElementById('wg-iface-modal-disabled').checked;
  1103. try {
  1104. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces`, {
  1105. method: 'POST',
  1106. headers: { 'Content-Type': 'application/json' },
  1107. body: JSON.stringify({
  1108. name,
  1109. listen_port: port,
  1110. address: addr,
  1111. mtu,
  1112. public_key: pub,
  1113. private_key: priv,
  1114. disabled
  1115. })
  1116. });
  1117. if (res.ok) {
  1118. showToast('WireGuard Saved', `Interface ${name} configured`, 'success');
  1119. closeAddWGInterfaceModal();
  1120. loadWireGuard(false);
  1121. fetchData(false);
  1122. }
  1123. } catch (err) {
  1124. showToast('Error', err.message, 'error');
  1125. }
  1126. }
  1127. async function startWGInterface(name) {
  1128. try {
  1129. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1130. if (res.ok) {
  1131. showToast('Interface UP', `Started WireGuard interface ${name}`, 'success');
  1132. loadWireGuard(false);
  1133. fetchData(false);
  1134. }
  1135. } catch (err) {
  1136. showToast('Error', err.message, 'error');
  1137. }
  1138. }
  1139. async function stopWGInterface(name) {
  1140. try {
  1141. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1142. if (res.ok) {
  1143. showToast('Interface DOWN', `Stopped WireGuard interface ${name}`, 'info');
  1144. loadWireGuard(false);
  1145. fetchData(false);
  1146. }
  1147. } catch (err) {
  1148. showToast('Error', err.message, 'error');
  1149. }
  1150. }
  1151. async function toggleWGInterfaceState(name, enable) {
  1152. try {
  1153. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/state`, {
  1154. method: 'POST',
  1155. headers: { 'Content-Type': 'application/json' },
  1156. body: JSON.stringify({ enabled: enable })
  1157. });
  1158. if (res.ok) {
  1159. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1160. loadWireGuard(false);
  1161. }
  1162. } catch (err) {
  1163. showToast('Error', err.message, 'error');
  1164. }
  1165. }
  1166. async function deleteWGInterface(name) {
  1167. if (!confirm(`Are you sure you want to delete WireGuard interface ${name}?`)) return;
  1168. try {
  1169. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1170. if (res.ok) {
  1171. showToast('Deleted', `Interface ${name} removed`, 'success');
  1172. loadWireGuard(false);
  1173. fetchData(false);
  1174. }
  1175. } catch (err) {
  1176. showToast('Error', err.message, 'error');
  1177. }
  1178. }
  1179. function openAddWGPeerModal() {
  1180. const sel = document.getElementById('wg-peer-modal-iface');
  1181. sel.innerHTML = '';
  1182. (state.wgInterfaces || []).forEach(i => {
  1183. const opt = document.createElement('option');
  1184. opt.value = i.name;
  1185. opt.innerText = `${i.name} (${i.address || 'No IP'})`;
  1186. sel.appendChild(opt);
  1187. });
  1188. if ((state.wgInterfaces || []).length === 0) {
  1189. showToast('No Interfaces', 'Please add a WireGuard interface first before adding peers', 'warning');
  1190. openAddWGInterfaceModal();
  1191. return;
  1192. }
  1193. document.getElementById('wg-peer-modal-name').value = '';
  1194. document.getElementById('wg-peer-modal-pubkey').value = '';
  1195. document.getElementById('wg-peer-modal-allowedips').value = '10.10.0.2/32';
  1196. document.getElementById('wg-peer-modal-endpoint').value = '';
  1197. document.getElementById('wg-peer-modal-keepalive').value = '25';
  1198. document.getElementById('wg-peer-modal-preshared').value = '';
  1199. document.getElementById('wg-peer-modal-disabled').checked = false;
  1200. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1201. }
  1202. function closeAddWGPeerModal() {
  1203. document.getElementById('wg-peer-modal').classList.add('hidden');
  1204. }
  1205. async function submitSaveWGPeer(e) {
  1206. e.preventDefault();
  1207. const iface = document.getElementById('wg-peer-modal-iface').value;
  1208. const name = document.getElementById('wg-peer-modal-name').value.trim();
  1209. const pub = document.getElementById('wg-peer-modal-pubkey').value.trim();
  1210. const allowed = document.getElementById('wg-peer-modal-allowedips').value.split(',').map(s => s.trim());
  1211. const ep = document.getElementById('wg-peer-modal-endpoint').value.trim();
  1212. const keepalive = parseInt(document.getElementById('wg-peer-modal-keepalive').value, 10) || 25;
  1213. const psk = document.getElementById('wg-peer-modal-preshared').value.trim();
  1214. const disabled = document.getElementById('wg-peer-modal-disabled').checked;
  1215. let epAddr = ep;
  1216. let epPort = 0;
  1217. if (ep.includes(':')) {
  1218. const parts = ep.split(':');
  1219. epAddr = parts[0];
  1220. epPort = parseInt(parts[1], 10) || 0;
  1221. }
  1222. try {
  1223. const res = await fetch(`${API_BASE}/vpn/wireguard/peers`, {
  1224. method: 'POST',
  1225. headers: { 'Content-Type': 'application/json' },
  1226. body: JSON.stringify({
  1227. interface: iface,
  1228. name,
  1229. public_key: pub,
  1230. allowed_ips: allowed,
  1231. endpoint_address: epAddr,
  1232. endpoint_port: epPort,
  1233. persistent_keepalive: keepalive,
  1234. preshared_key: psk,
  1235. disabled
  1236. })
  1237. });
  1238. if (res.ok) {
  1239. showToast('Peer Saved', `Peer ${name} added to ${iface}`, 'success');
  1240. closeAddWGPeerModal();
  1241. loadWireGuard(false);
  1242. }
  1243. } catch (err) {
  1244. showToast('Error', err.message, 'error');
  1245. }
  1246. }
  1247. async function deleteWGPeer(iface, pubkey) {
  1248. if (!confirm(`Are you sure you want to remove peer from ${iface}?`)) return;
  1249. try {
  1250. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/${encodeURIComponent(iface)}/${encodeURIComponent(pubkey)}`, {
  1251. method: 'DELETE'
  1252. });
  1253. if (res.ok) {
  1254. showToast('Peer Deleted', 'WireGuard peer removed', 'success');
  1255. loadWireGuard(false);
  1256. }
  1257. } catch (err) {
  1258. showToast('Error', err.message, 'error');
  1259. }
  1260. }
  1261. // ======================== IPSec Multi-Tunnel ========================
  1262. async function loadIPSec(populateInputs = true) {
  1263. try {
  1264. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`);
  1265. const list = await res.json();
  1266. state.ipsecTunnels = Array.isArray(list) ? list : [];
  1267. const activeCount = state.ipsecTunnels.filter(t => t.running || t.status === 'ESTABLISHED').length;
  1268. const badge = document.getElementById('ipsec-sas-badge');
  1269. if (badge) badge.innerText = `${activeCount} Active SAs`;
  1270. const tbody = document.getElementById('ipsec-table-body');
  1271. const empty = document.getElementById('ipsec-empty');
  1272. if (!tbody) return;
  1273. tbody.innerHTML = '';
  1274. if (state.ipsecTunnels.length === 0) {
  1275. if (empty) empty.classList.remove('hidden');
  1276. } else {
  1277. if (empty) empty.classList.add('hidden');
  1278. state.ipsecTunnels.forEach(c => {
  1279. const isEstablished = c.running || c.status === 'ESTABLISHED';
  1280. const tr = document.createElement('tr');
  1281. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1282. tr.innerHTML = `
  1283. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isEstablished, c.disabled)}</td>
  1284. <td class="py-2.5 px-4 font-bold text-white">${c.name}</td>
  1285. <td class="py-2.5 px-4 text-emerald-400 font-mono">${c.local_subnet || '-'}</td>
  1286. <td class="py-2.5 px-4 text-slate-300 font-mono">${c.remote_addrs || '-'}</td>
  1287. <td class="py-2.5 px-4 text-cyan-400 font-mono">${c.remote_subnet || '-'}</td>
  1288. <td class="py-2.5 px-4 font-sans">
  1289. <span class="px-2 py-0.5 rounded-full text-[10px] font-semibold ${
  1290. isEstablished ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30' : 'bg-slate-800 text-slate-400'
  1291. }">${c.status || (isEstablished ? 'ESTABLISHED' : 'DISCONNECTED')}</span>
  1292. </td>
  1293. <td class="py-2.5 px-4 text-right space-x-2 font-sans">
  1294. ${isEstablished ? `
  1295. <button onclick="stopIPSecTunnel('${c.name}')" class="text-xs text-rose-400 hover:text-rose-300">Terminate</button>
  1296. ` : `
  1297. <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>
  1298. `}
  1299. <button onclick="toggleIPSecState('${c.name}', ${c.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1300. ${c.disabled ? 'Enable' : 'Disable'}
  1301. </button>
  1302. <button onclick="openEditIPSecModal('${c.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1303. <button onclick="deleteIPSecConn('${c.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1304. </td>
  1305. `;
  1306. tbody.appendChild(tr);
  1307. });
  1308. }
  1309. } catch (err) {
  1310. console.error('Failed to load IPSec:', err);
  1311. }
  1312. }
  1313. function openAddIPSecModal() {
  1314. document.getElementById('ipsec-modal-title').innerText = 'Configure IPSec IKEv2 Tunnel';
  1315. document.getElementById('ipsec-modal-name').value = `ipsec-${(state.ipsecTunnels || []).length + 1}`;
  1316. document.getElementById('ipsec-modal-name').readOnly = false;
  1317. document.getElementById('ipsec-modal-localts').value = '192.168.10.0/24';
  1318. document.getElementById('ipsec-modal-remotets').value = '192.168.20.0/24';
  1319. document.getElementById('ipsec-modal-remotegw').value = '';
  1320. document.getElementById('ipsec-modal-psk').value = '';
  1321. document.getElementById('ipsec-modal-ikeprop').value = 'aes256-sha256-modp2048,default';
  1322. document.getElementById('ipsec-modal-espprop').value = 'aes256-sha256-modp2048,default';
  1323. document.getElementById('ipsec-modal-autostart').checked = true;
  1324. document.getElementById('ipsec-modal-disabled').checked = false;
  1325. document.getElementById('ipsec-modal').classList.remove('hidden');
  1326. }
  1327. function openEditIPSecModal(name) {
  1328. const conn = (state.ipsecTunnels || []).find(c => c.name === name);
  1329. if (!conn) return;
  1330. document.getElementById('ipsec-modal-title').innerText = `Edit IPSec Tunnel: ${name}`;
  1331. document.getElementById('ipsec-modal-name').value = conn.name;
  1332. document.getElementById('ipsec-modal-name').readOnly = true;
  1333. document.getElementById('ipsec-modal-localts').value = conn.local_subnet || '';
  1334. document.getElementById('ipsec-modal-remotets').value = conn.remote_subnet || '';
  1335. document.getElementById('ipsec-modal-remotegw').value = conn.remote_addrs || '';
  1336. document.getElementById('ipsec-modal-psk').value = conn.preshared_key || '';
  1337. document.getElementById('ipsec-modal-ikeprop').value = conn.ike_proposals || 'aes256-sha256-modp2048,default';
  1338. document.getElementById('ipsec-modal-espprop').value = conn.esp_proposals || 'aes256-sha256-modp2048,default';
  1339. document.getElementById('ipsec-modal-autostart').checked = conn.auto_start ?? true;
  1340. document.getElementById('ipsec-modal-disabled').checked = !!conn.disabled;
  1341. document.getElementById('ipsec-modal').classList.remove('hidden');
  1342. }
  1343. function closeAddIPSecModal() {
  1344. document.getElementById('ipsec-modal').classList.add('hidden');
  1345. }
  1346. async function submitSaveIPSec(e) {
  1347. e.preventDefault();
  1348. const name = document.getElementById('ipsec-modal-name').value.trim();
  1349. const localts = document.getElementById('ipsec-modal-localts').value.trim();
  1350. const remotets = document.getElementById('ipsec-modal-remotets').value.trim();
  1351. const remotegw = document.getElementById('ipsec-modal-remotegw').value.trim();
  1352. const psk = document.getElementById('ipsec-modal-psk').value;
  1353. const ike = document.getElementById('ipsec-modal-ikeprop').value.trim();
  1354. const esp = document.getElementById('ipsec-modal-espprop').value.trim();
  1355. const autostart = document.getElementById('ipsec-modal-autostart').checked;
  1356. const disabled = document.getElementById('ipsec-modal-disabled').checked;
  1357. try {
  1358. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`, {
  1359. method: 'POST',
  1360. headers: { 'Content-Type': 'application/json' },
  1361. body: JSON.stringify({
  1362. name,
  1363. local_addrs: '%any',
  1364. remote_addrs: remotegw,
  1365. local_subnet: localts,
  1366. remote_subnet: remotets,
  1367. preshared_key: psk,
  1368. ike_proposals: ike,
  1369. esp_proposals: esp,
  1370. auto_start: autostart,
  1371. disabled
  1372. })
  1373. });
  1374. if (res.ok) {
  1375. showToast('IPSec Saved', `Tunnel ${name} configured`, 'success');
  1376. closeAddIPSecModal();
  1377. loadIPSec(false);
  1378. fetchData(false);
  1379. }
  1380. } catch (err) {
  1381. showToast('Error', err.message, 'error');
  1382. }
  1383. }
  1384. async function startIPSecTunnel(name) {
  1385. try {
  1386. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1387. if (res.ok) {
  1388. showToast('Initiating Tunnel', `Attempting SA handshake for ${name}...`, 'info');
  1389. setTimeout(() => loadIPSec(false), 2000);
  1390. }
  1391. } catch (err) {
  1392. showToast('Error', err.message, 'error');
  1393. }
  1394. }
  1395. async function stopIPSecTunnel(name) {
  1396. try {
  1397. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1398. if (res.ok) {
  1399. showToast('Terminated', `IPSec SA for ${name} closed`, 'info');
  1400. loadIPSec(false);
  1401. }
  1402. } catch (err) {
  1403. showToast('Error', err.message, 'error');
  1404. }
  1405. }
  1406. async function toggleIPSecState(name, enable) {
  1407. try {
  1408. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/state`, {
  1409. method: 'POST',
  1410. headers: { 'Content-Type': 'application/json' },
  1411. body: JSON.stringify({ enabled: enable })
  1412. });
  1413. if (res.ok) {
  1414. showToast(enable ? 'Enabled' : 'Disabled', `IPSec tunnel ${name} updated`, 'info');
  1415. loadIPSec(false);
  1416. }
  1417. } catch (err) {
  1418. showToast('Error', err.message, 'error');
  1419. }
  1420. }
  1421. async function deleteIPSecConn(name) {
  1422. if (!confirm(`Are you sure you want to delete IPSec tunnel ${name}?`)) return;
  1423. try {
  1424. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1425. if (res.ok) {
  1426. showToast('Deleted', `IPSec connection ${name} removed`, 'success');
  1427. loadIPSec(false);
  1428. fetchData(false);
  1429. }
  1430. } catch (err) {
  1431. showToast('Error', err.message, 'error');
  1432. }
  1433. }
  1434. // ======================== L2TP Multi-Instance ========================
  1435. async function loadL2TP(populateInputs = true) {
  1436. try {
  1437. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`);
  1438. const list = await res.json();
  1439. state.l2tpList = Array.isArray(list) ? list : [];
  1440. const badge = document.getElementById('l2tp-count-badge');
  1441. if (badge) badge.innerText = `${state.l2tpList.length} Client${state.l2tpList.length !== 1 ? 's' : ''}`;
  1442. const tbody = document.getElementById('l2tp-table-body');
  1443. const empty = document.getElementById('l2tp-empty');
  1444. if (!tbody) return;
  1445. tbody.innerHTML = '';
  1446. if (state.l2tpList.length === 0) {
  1447. if (empty) empty.classList.remove('hidden');
  1448. } else {
  1449. if (empty) empty.classList.add('hidden');
  1450. state.l2tpList.forEach(inst => {
  1451. const tr = document.createElement('tr');
  1452. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1453. tr.innerHTML = `
  1454. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1455. <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
  1456. <td class="py-2.5 px-3 text-cyan-400 font-mono">${inst.connect_to}</td>
  1457. <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
  1458. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
  1459. <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
  1460. <td class="py-2.5 px-3 text-center">
  1461. <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'}">
  1462. ${inst.default_route ? 'Yes' : 'No'}
  1463. </span>
  1464. </td>
  1465. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1466. ${inst.running ? `
  1467. <button onclick="disconnectL2TPInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1468. ` : `
  1469. <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>
  1470. `}
  1471. <button onclick="toggleL2TPState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1472. ${inst.disabled ? 'Enable' : 'Disable'}
  1473. </button>
  1474. <button onclick="openEditL2TPModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1475. <button onclick="deleteL2TPInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1476. </td>
  1477. `;
  1478. tbody.appendChild(tr);
  1479. });
  1480. }
  1481. } catch (err) {
  1482. console.error('Failed to load L2TP:', err);
  1483. }
  1484. }
  1485. function openAddL2TPModal() {
  1486. document.getElementById('l2tp-modal-title').innerText = 'Add L2TP Client Interface';
  1487. document.getElementById('l2tp-modal-name').value = `l2tp-out${(state.l2tpList || []).length + 1}`;
  1488. document.getElementById('l2tp-modal-name').readOnly = false;
  1489. document.getElementById('l2tp-modal-server').value = '';
  1490. document.getElementById('l2tp-modal-user').value = '';
  1491. document.getElementById('l2tp-modal-pass').value = '';
  1492. document.getElementById('l2tp-modal-ipsec').value = '';
  1493. document.getElementById('l2tp-modal-defroute').checked = true;
  1494. document.getElementById('l2tp-modal-disabled').checked = false;
  1495. document.getElementById('l2tp-modal').classList.remove('hidden');
  1496. }
  1497. function openEditL2TPModal(name) {
  1498. const inst = (state.l2tpList || []).find(i => i.name === name);
  1499. if (!inst) return;
  1500. document.getElementById('l2tp-modal-title').innerText = `Edit L2TP Client: ${name}`;
  1501. document.getElementById('l2tp-modal-name').value = inst.name;
  1502. document.getElementById('l2tp-modal-name').readOnly = true;
  1503. document.getElementById('l2tp-modal-server').value = inst.connect_to || '';
  1504. document.getElementById('l2tp-modal-user').value = inst.username || '';
  1505. document.getElementById('l2tp-modal-pass').value = inst.password || '';
  1506. document.getElementById('l2tp-modal-ipsec').value = inst.ipsec_secret || '';
  1507. document.getElementById('l2tp-modal-defroute').checked = inst.default_route ?? true;
  1508. document.getElementById('l2tp-modal-disabled').checked = !!inst.disabled;
  1509. document.getElementById('l2tp-modal').classList.remove('hidden');
  1510. }
  1511. function closeL2TPModal() {
  1512. document.getElementById('l2tp-modal').classList.add('hidden');
  1513. }
  1514. async function submitSaveL2TP(e) {
  1515. e.preventDefault();
  1516. const name = document.getElementById('l2tp-modal-name').value.trim();
  1517. const server = document.getElementById('l2tp-modal-server').value.trim();
  1518. const user = document.getElementById('l2tp-modal-user').value.trim();
  1519. const pass = document.getElementById('l2tp-modal-pass').value;
  1520. const ipsec = document.getElementById('l2tp-modal-ipsec').value;
  1521. const defRoute = document.getElementById('l2tp-modal-defroute').checked;
  1522. const disabled = document.getElementById('l2tp-modal-disabled').checked;
  1523. try {
  1524. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`, {
  1525. method: 'POST',
  1526. headers: { 'Content-Type': 'application/json' },
  1527. body: JSON.stringify({
  1528. name,
  1529. connect_to: server,
  1530. username: user,
  1531. password: pass,
  1532. ipsec_secret: ipsec,
  1533. default_route: defRoute,
  1534. disabled
  1535. })
  1536. });
  1537. if (res.ok) {
  1538. showToast('L2TP Saved', `Client ${name} configuration saved`, 'success');
  1539. closeL2TPModal();
  1540. loadL2TP(false);
  1541. fetchData(false);
  1542. }
  1543. } catch (err) {
  1544. showToast('Error', err.message, 'error');
  1545. }
  1546. }
  1547. async function connectL2TPInstance(name) {
  1548. try {
  1549. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1550. if (res.ok) {
  1551. showToast('Connecting', `Dialing L2TP ${name}...`, 'info');
  1552. setTimeout(() => loadL2TP(false), 2000);
  1553. }
  1554. } catch (err) {
  1555. showToast('Error', err.message, 'error');
  1556. }
  1557. }
  1558. async function disconnectL2TPInstance(name) {
  1559. try {
  1560. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1561. if (res.ok) {
  1562. showToast('Disconnected', `L2TP tunnel ${name} terminated`, 'info');
  1563. loadL2TP(false);
  1564. }
  1565. } catch (err) {
  1566. showToast('Error', err.message, 'error');
  1567. }
  1568. }
  1569. async function toggleL2TPState(name, enable) {
  1570. try {
  1571. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/state`, {
  1572. method: 'POST',
  1573. headers: { 'Content-Type': 'application/json' },
  1574. body: JSON.stringify({ enabled: enable })
  1575. });
  1576. if (res.ok) {
  1577. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1578. loadL2TP(false);
  1579. }
  1580. } catch (err) {
  1581. showToast('Error', err.message, 'error');
  1582. }
  1583. }
  1584. async function deleteL2TPInstance(name) {
  1585. if (!confirm(`Are you sure you want to delete L2TP client ${name}?`)) return;
  1586. try {
  1587. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1588. if (res.ok) {
  1589. showToast('Deleted', `L2TP client ${name} removed`, 'success');
  1590. loadL2TP(false);
  1591. fetchData(false);
  1592. }
  1593. } catch (err) {
  1594. showToast('Error', err.message, 'error');
  1595. }
  1596. }
  1597. // ======================== PPTP Multi-Instance ========================
  1598. async function loadPPTP(populateInputs = true) {
  1599. try {
  1600. const res = await fetch(`${API_BASE}/vpn/pptp/clients`);
  1601. const list = await res.json();
  1602. state.pptpList = Array.isArray(list) ? list : [];
  1603. const badge = document.getElementById('pptp-count-badge');
  1604. if (badge) badge.innerText = `${state.pptpList.length} Client${state.pptpList.length !== 1 ? 's' : ''}`;
  1605. const tbody = document.getElementById('pptp-table-body');
  1606. const empty = document.getElementById('pptp-empty');
  1607. if (!tbody) return;
  1608. tbody.innerHTML = '';
  1609. if (state.pptpList.length === 0) {
  1610. if (empty) empty.classList.remove('hidden');
  1611. } else {
  1612. if (empty) empty.classList.add('hidden');
  1613. state.pptpList.forEach(inst => {
  1614. const tr = document.createElement('tr');
  1615. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1616. tr.innerHTML = `
  1617. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1618. <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
  1619. <td class="py-2.5 px-3 text-purple-400 font-mono">${inst.connect_to}</td>
  1620. <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
  1621. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
  1622. <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
  1623. <td class="py-2.5 px-3 text-center">
  1624. <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'}">
  1625. ${inst.require_mppe ? 'MPPE-128' : 'None'}
  1626. </span>
  1627. </td>
  1628. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1629. ${inst.running ? `
  1630. <button onclick="disconnectPPTPInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1631. ` : `
  1632. <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>
  1633. `}
  1634. <button onclick="togglePPTPState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1635. ${inst.disabled ? 'Enable' : 'Disable'}
  1636. </button>
  1637. <button onclick="openEditPPTPModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1638. <button onclick="deletePPTPInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1639. </td>
  1640. `;
  1641. tbody.appendChild(tr);
  1642. });
  1643. }
  1644. } catch (err) {
  1645. console.error('Failed to load PPTP:', err);
  1646. }
  1647. }
  1648. function openAddPPTPModal() {
  1649. document.getElementById('pptp-modal-title').innerText = 'Add PPTP Client Interface';
  1650. document.getElementById('pptp-modal-name').value = `pptp-out${(state.pptpList || []).length + 1}`;
  1651. document.getElementById('pptp-modal-name').readOnly = false;
  1652. document.getElementById('pptp-modal-server').value = '';
  1653. document.getElementById('pptp-modal-user').value = '';
  1654. document.getElementById('pptp-modal-pass').value = '';
  1655. document.getElementById('pptp-modal-mppe').checked = true;
  1656. document.getElementById('pptp-modal-defroute').checked = true;
  1657. document.getElementById('pptp-modal-disabled').checked = false;
  1658. document.getElementById('pptp-modal').classList.remove('hidden');
  1659. }
  1660. function openEditPPTPModal(name) {
  1661. const inst = (state.pptpList || []).find(i => i.name === name);
  1662. if (!inst) return;
  1663. document.getElementById('pptp-modal-title').innerText = `Edit PPTP Client: ${name}`;
  1664. document.getElementById('pptp-modal-name').value = inst.name;
  1665. document.getElementById('pptp-modal-name').readOnly = true;
  1666. document.getElementById('pptp-modal-server').value = inst.connect_to || '';
  1667. document.getElementById('pptp-modal-user').value = inst.username || '';
  1668. document.getElementById('pptp-modal-pass').value = inst.password || '';
  1669. document.getElementById('pptp-modal-mppe').checked = inst.require_mppe ?? true;
  1670. document.getElementById('pptp-modal-defroute').checked = inst.default_route ?? true;
  1671. document.getElementById('pptp-modal-disabled').checked = !!inst.disabled;
  1672. document.getElementById('pptp-modal').classList.remove('hidden');
  1673. }
  1674. function closePPTPModal() {
  1675. document.getElementById('pptp-modal').classList.add('hidden');
  1676. }
  1677. async function submitSavePPTP(e) {
  1678. e.preventDefault();
  1679. const name = document.getElementById('pptp-modal-name').value.trim();
  1680. const server = document.getElementById('pptp-modal-server').value.trim();
  1681. const user = document.getElementById('pptp-modal-user').value.trim();
  1682. const pass = document.getElementById('pptp-modal-pass').value;
  1683. const mppe = document.getElementById('pptp-modal-mppe').checked;
  1684. const defRoute = document.getElementById('pptp-modal-defroute').checked;
  1685. const disabled = document.getElementById('pptp-modal-disabled').checked;
  1686. try {
  1687. const res = await fetch(`${API_BASE}/vpn/pptp/clients`, {
  1688. method: 'POST',
  1689. headers: { 'Content-Type': 'application/json' },
  1690. body: JSON.stringify({
  1691. name,
  1692. connect_to: server,
  1693. username: user,
  1694. password: pass,
  1695. require_mppe: mppe,
  1696. default_route: defRoute,
  1697. auto_reconnect: true,
  1698. disabled
  1699. })
  1700. });
  1701. if (res.ok) {
  1702. showToast('PPTP Saved', `Client ${name} configuration saved`, 'success');
  1703. closePPTPModal();
  1704. loadPPTP(false);
  1705. fetchData(false);
  1706. }
  1707. } catch (err) {
  1708. showToast('Error', err.message, 'error');
  1709. }
  1710. }
  1711. async function connectPPTPInstance(name) {
  1712. try {
  1713. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1714. if (res.ok) {
  1715. showToast('Connecting', `Dialing PPTP ${name}...`, 'info');
  1716. setTimeout(() => loadPPTP(false), 2000);
  1717. }
  1718. } catch (err) {
  1719. showToast('Error', err.message, 'error');
  1720. }
  1721. }
  1722. async function disconnectPPTPInstance(name) {
  1723. try {
  1724. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1725. if (res.ok) {
  1726. showToast('Disconnected', `PPTP tunnel ${name} terminated`, 'info');
  1727. loadPPTP(false);
  1728. }
  1729. } catch (err) {
  1730. showToast('Error', err.message, 'error');
  1731. }
  1732. }
  1733. async function togglePPTPState(name, enable) {
  1734. try {
  1735. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/state`, {
  1736. method: 'POST',
  1737. headers: { 'Content-Type': 'application/json' },
  1738. body: JSON.stringify({ enabled: enable })
  1739. });
  1740. if (res.ok) {
  1741. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1742. loadPPTP(false);
  1743. }
  1744. } catch (err) {
  1745. showToast('Error', err.message, 'error');
  1746. }
  1747. }
  1748. async function deletePPTPInstance(name) {
  1749. if (!confirm(`Are you sure you want to delete PPTP client ${name}?`)) return;
  1750. try {
  1751. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1752. if (res.ok) {
  1753. showToast('Deleted', `PPTP client ${name} removed`, 'success');
  1754. loadPPTP(false);
  1755. fetchData(false);
  1756. }
  1757. } catch (err) {
  1758. showToast('Error', err.message, 'error');
  1759. }
  1760. }
  1761. // ---------------- Modal & Helper Functions ----------------
  1762. function openVlanModal(defaultParent = '') {
  1763. const select = document.getElementById('vlan-parent');
  1764. select.innerHTML = '';
  1765. const allIfaces = state.interfaces || [];
  1766. const eligible = allIfaces.filter(i => !i.is_vlan && i.name !== 'lo');
  1767. if (eligible.length === 0) {
  1768. allIfaces.forEach(i => eligible.push(i));
  1769. }
  1770. eligible.forEach(i => {
  1771. const opt = document.createElement('option');
  1772. opt.value = i.name;
  1773. opt.innerText = `${i.name} (${i.role || 'Interface'} - ${i.state})`;
  1774. if (i.name === defaultParent) opt.selected = true;
  1775. select.appendChild(opt);
  1776. });
  1777. document.getElementById('vlan-id').value = '';
  1778. document.getElementById('vlan-name').value = '';
  1779. document.getElementById('vlan-ip').value = '';
  1780. document.getElementById('vlan-desc').value = '';
  1781. autoSuggestVlanName();
  1782. document.getElementById('vlan-modal').classList.remove('hidden');
  1783. }
  1784. function closeVlanModal() {
  1785. document.getElementById('vlan-modal').classList.add('hidden');
  1786. }
  1787. function autoSuggestVlanName() {
  1788. const parent = document.getElementById('vlan-parent').value;
  1789. const id = document.getElementById('vlan-id').value;
  1790. const nameInput = document.getElementById('vlan-name');
  1791. if (parent && id) nameInput.placeholder = `${parent}.${id}`;
  1792. }
  1793. function setSubnetPreset(cidr) {
  1794. const ipInput = document.getElementById('vlan-ip');
  1795. const id = document.getElementById('vlan-id').value || '10';
  1796. ipInput.value = `192.168.${id}.1${cidr}`;
  1797. }
  1798. async function submitCreateVlan(e) {
  1799. e.preventDefault();
  1800. const btn = document.getElementById('vlan-submit-btn');
  1801. btn.disabled = true;
  1802. btn.innerText = 'Creating...';
  1803. const parent = document.getElementById('vlan-parent').value;
  1804. const id = parseInt(document.getElementById('vlan-id').value, 10);
  1805. const name = document.getElementById('vlan-name').value.trim();
  1806. const ip = document.getElementById('vlan-ip').value.trim();
  1807. const role = document.getElementById('vlan-role').value;
  1808. const desc = document.getElementById('vlan-desc').value.trim();
  1809. try {
  1810. const res = await fetch(`${API_BASE}/vlans`, {
  1811. method: 'POST',
  1812. headers: { 'Content-Type': 'application/json' },
  1813. body: JSON.stringify({
  1814. parent_name: parent,
  1815. vlan_id: id,
  1816. name: name,
  1817. ip_address: ip,
  1818. role: role,
  1819. description: desc,
  1820. mtu: 1500,
  1821. auto_up: true
  1822. })
  1823. });
  1824. const data = await res.json();
  1825. if (res.ok) {
  1826. showToast('VLAN Created', `Created ${data.name} (VLAN ${data.vlan_id})`, 'success');
  1827. state.expandedParents.add(parent);
  1828. closeVlanModal();
  1829. await fetchData(true);
  1830. if (state.activeTab !== 'interfaces') navigate('interfaces');
  1831. } else {
  1832. showToast('Creation Failed', data.message || 'Failed to create VLAN', 'error');
  1833. }
  1834. } catch (err) {
  1835. showToast('Error', err.message, 'error');
  1836. } finally {
  1837. btn.disabled = false;
  1838. btn.innerText = 'Create VLAN';
  1839. }
  1840. }
  1841. async function confirmDeleteVlan(name) {
  1842. if (!confirm(`Delete VLAN interface ${name}?`)) return;
  1843. try {
  1844. const res = await fetch(`${API_BASE}/vlans/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1845. if (res.ok) {
  1846. showToast('VLAN Deleted', `Interface ${name} removed`, 'success');
  1847. closeIfaceModal();
  1848. fetchData(true);
  1849. }
  1850. } catch (err) {
  1851. showToast('Error', err.message, 'error');
  1852. }
  1853. }
  1854. function openIfaceModal(name) {
  1855. const iface = (state.interfaces || []).find(i => i.name === name);
  1856. if (!iface) return;
  1857. state.currentModalIface = iface.name;
  1858. document.getElementById('modal-iface-name').innerText = iface.name;
  1859. document.getElementById('modal-iface-badge').innerText = iface.is_vlan ? `VLAN ${iface.vlan_id}` : iface.type;
  1860. document.getElementById('modal-iface-mtu').value = iface.mtu;
  1861. document.getElementById('modal-iface-role').value = iface.role || 'LAN';
  1862. document.getElementById('modal-iface-desc').value = iface.description || '';
  1863. const delBtn = document.getElementById('modal-delete-vlan-btn');
  1864. if (iface.is_vlan) {
  1865. delBtn.classList.remove('hidden');
  1866. } else {
  1867. delBtn.classList.add('hidden');
  1868. }
  1869. renderModalIPs(iface);
  1870. document.getElementById('iface-modal').classList.remove('hidden');
  1871. }
  1872. function renderModalIPs(iface) {
  1873. const container = document.getElementById('modal-ip-list');
  1874. container.innerHTML = '';
  1875. const addrs = [...(iface.ipv4 || []), ...(iface.ipv6 || [])];
  1876. if (addrs.length === 0) {
  1877. container.innerHTML = `<span class="text-slate-500 text-xs font-sans">No IP addresses currently bound</span>`;
  1878. return;
  1879. }
  1880. addrs.forEach(addr => {
  1881. const row = document.createElement('div');
  1882. row.className = 'flex items-center justify-between p-2 rounded bg-slate-900 border border-slate-800';
  1883. row.innerHTML = `
  1884. <span class="text-white">${addr}</span>
  1885. <button onclick="removeInterfaceIP('${addr}')" class="text-[11px] text-rose-400 hover:text-rose-300 font-sans">Remove</button>
  1886. `;
  1887. container.appendChild(row);
  1888. });
  1889. }
  1890. function closeIfaceModal() {
  1891. document.getElementById('iface-modal').classList.add('hidden');
  1892. state.currentModalIface = null;
  1893. }
  1894. async function setIfaceState(name, newState) {
  1895. await toggleInterfaceState(name, newState);
  1896. const updated = (state.interfaces || []).find(i => i.name === name);
  1897. if (updated) openIfaceModal(name);
  1898. }
  1899. async function applyMTU() {
  1900. const mtu = parseInt(document.getElementById('modal-iface-mtu').value, 10);
  1901. try {
  1902. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/mtu`, {
  1903. method: 'POST',
  1904. headers: { 'Content-Type': 'application/json' },
  1905. body: JSON.stringify({ mtu })
  1906. });
  1907. if (res.ok) {
  1908. showToast('MTU Applied', `Set MTU to ${mtu} on ${state.currentModalIface}`, 'success');
  1909. fetchData(false);
  1910. }
  1911. } catch (err) {
  1912. showToast('Error', err.message, 'error');
  1913. }
  1914. }
  1915. async function addInterfaceIP() {
  1916. const ip = document.getElementById('modal-new-ip').value.trim();
  1917. if (!ip) return;
  1918. try {
  1919. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  1920. method: 'POST',
  1921. headers: { 'Content-Type': 'application/json' },
  1922. body: JSON.stringify({ ip })
  1923. });
  1924. if (res.ok) {
  1925. showToast('IP Added', `Bound ${ip} to ${state.currentModalIface}`, 'success');
  1926. document.getElementById('modal-new-ip').value = '';
  1927. await fetchData(false);
  1928. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  1929. if (iface) renderModalIPs(iface);
  1930. } else {
  1931. const err = await res.json();
  1932. showToast('Error', err.error || err.message || 'Failed to add IP address', 'error');
  1933. }
  1934. } catch (err) {
  1935. showToast('Error', err.message, 'error');
  1936. }
  1937. }
  1938. async function removeInterfaceIP(ip) {
  1939. if (!confirm(`Remove IP ${ip}?`)) return;
  1940. try {
  1941. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  1942. method: 'DELETE',
  1943. headers: { 'Content-Type': 'application/json' },
  1944. body: JSON.stringify({ ip })
  1945. });
  1946. if (res.ok) {
  1947. showToast('IP Removed', `Removed ${ip}`, 'success');
  1948. await fetchData(false);
  1949. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  1950. if (iface) renderModalIPs(iface);
  1951. }
  1952. } catch (err) {
  1953. showToast('Error', err.message, 'error');
  1954. }
  1955. }
  1956. async function saveInterfaceMetadata() {
  1957. const role = document.getElementById('modal-iface-role').value;
  1958. const desc = document.getElementById('modal-iface-desc').value.trim();
  1959. try {
  1960. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/metadata`, {
  1961. method: 'POST',
  1962. headers: { 'Content-Type': 'application/json' },
  1963. body: JSON.stringify({ role, description: desc })
  1964. });
  1965. if (res.ok) {
  1966. showToast('Saved', 'Metadata updated', 'success');
  1967. closeIfaceModal();
  1968. fetchData(false);
  1969. }
  1970. } catch (err) {
  1971. showToast('Error', err.message, 'error');
  1972. }
  1973. }
  1974. // ======================== MIKROTIK FIREWALL (/ip firewall) ========================
  1975. state.fwSubTab = 'filter';
  1976. state.routesSubTab = 'routes';
  1977. function renderRuleFlag(disabled, hasComment) {
  1978. let flags = '';
  1979. if (disabled) flags += '<span class="text-rose-400 font-bold" title="Disabled">X</span>';
  1980. if (hasComment) flags += '<span class="text-amber-400 font-bold ml-1" title="Has Comment">C</span>';
  1981. return flags || '<span class="text-slate-600">-</span>';
  1982. }
  1983. function renderActionBadge(action) {
  1984. const act = (action || '').toLowerCase();
  1985. let color = 'bg-slate-800 text-slate-300';
  1986. if (act === 'accept') color = 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30';
  1987. else if (act === 'drop' || act === 'reject') color = 'bg-rose-500/20 text-rose-300 border border-rose-500/30';
  1988. else if (act === 'masquerade' || act === 'src-nat' || act === 'dst-nat') color = 'bg-amber-500/20 text-amber-300 border border-amber-500/30';
  1989. else if (act.startsWith('mark-')) color = 'bg-purple-500/20 text-purple-300 border border-purple-500/30';
  1990. else if (act === 'log') color = 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30';
  1991. return `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold ${color}">${action}</span>`;
  1992. }
  1993. function switchFWSubTab(tab) {
  1994. state.fwSubTab = tab;
  1995. const tabs = ['filter', 'nat', 'mangle', 'addrlist', 'geo', 'connections'];
  1996. tabs.forEach(t => {
  1997. const panel = document.getElementById(`fw-subtab-${t}`);
  1998. const btn = document.getElementById(`fw-subtab-btn-${t}`);
  1999. if (panel) {
  2000. if (t === tab) panel.classList.remove('hidden');
  2001. else panel.classList.add('hidden');
  2002. }
  2003. if (btn) {
  2004. if (t === tab) {
  2005. 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';
  2006. } else {
  2007. 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';
  2008. }
  2009. }
  2010. });
  2011. const addBtn = document.getElementById('fw-primary-add-btn');
  2012. if (addBtn) {
  2013. if (tab === 'filter') addBtn.innerHTML = '<span>+ Add Filter Rule</span>';
  2014. else if (tab === 'nat') addBtn.innerHTML = '<span>+ Add NAT Rule</span>';
  2015. else if (tab === 'mangle') addBtn.innerHTML = '<span>+ Add Mangle Rule</span>';
  2016. else if (tab === 'addrlist') addBtn.innerHTML = '<span>+ Add Address List</span>';
  2017. else if (tab === 'geo') addBtn.innerHTML = '<span>⚙️ Schedule Settings</span>';
  2018. else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
  2019. }
  2020. if (tab === 'geo') loadGeoIP();
  2021. if (tab === 'connections') loadConnections();
  2022. }
  2023. function openCurrentFWModal() {
  2024. if (state.fwSubTab === 'filter') openAddFilterModal();
  2025. else if (state.fwSubTab === 'nat') openAddNATModal();
  2026. else if (state.fwSubTab === 'mangle') openAddMangleModal();
  2027. else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
  2028. else if (state.fwSubTab === 'geo') openGeoIntervalModal();
  2029. else if (state.fwSubTab === 'connections') loadConnections();
  2030. }
  2031. async function loadFirewall(populateDropdowns = true) {
  2032. try {
  2033. const [summaryRes, filterRes, natRes, mangleRes, addrlistRes, geoStatusRes, geoCountriesRes] = await Promise.all([
  2034. fetch(`${API_BASE}/firewall/summary`),
  2035. fetch(`${API_BASE}/firewall/filter`),
  2036. fetch(`${API_BASE}/firewall/nat`),
  2037. fetch(`${API_BASE}/firewall/mangle`),
  2038. fetch(`${API_BASE}/firewall/address-lists`),
  2039. fetch(`${API_BASE}/firewall/geoip/status`),
  2040. fetch(`${API_BASE}/firewall/geoip/countries`)
  2041. ]);
  2042. if (summaryRes.ok) state.fwSummary = await summaryRes.json();
  2043. if (filterRes.ok) state.filterRules = await filterRes.json();
  2044. if (natRes.ok) state.natRules = await natRes.json();
  2045. if (mangleRes.ok) state.mangleRules = await mangleRes.json();
  2046. if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
  2047. if (geoStatusRes.ok) state.geoStatus = await geoStatusRes.json();
  2048. if (geoCountriesRes.ok) state.geoCountries = await geoCountriesRes.json();
  2049. // Badges
  2050. const bFilter = document.getElementById('fw-badge-filter');
  2051. if (bFilter) bFilter.innerText = (state.filterRules || []).length;
  2052. const bNat = document.getElementById('fw-badge-nat');
  2053. if (bNat) bNat.innerText = (state.natRules || []).length;
  2054. const bMangle = document.getElementById('fw-badge-mangle');
  2055. if (bMangle) bMangle.innerText = (state.mangleRules || []).length;
  2056. const bAddr = document.getElementById('fw-badge-addrlist');
  2057. if (bAddr) bAddr.innerText = (state.addressLists || []).length;
  2058. const bGeo = document.getElementById('fw-badge-geo');
  2059. if (bGeo) bGeo.innerText = state.geoStatus?.enabled_count || 0;
  2060. renderFilterRules();
  2061. renderNATRules();
  2062. renderMangleRules();
  2063. renderAddressLists();
  2064. renderGeoCountries();
  2065. if (state.fwSubTab === 'connections') {
  2066. loadConnections();
  2067. }
  2068. } catch (err) {
  2069. console.error('Failed to load firewall:', err);
  2070. }
  2071. }
  2072. // ----------------- Filter Rules -----------------
  2073. function renderFilterRules() {
  2074. const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
  2075. const tbody = document.getElementById('filter-table-body');
  2076. const empty = document.getElementById('filter-empty');
  2077. if (!tbody) return;
  2078. tbody.innerHTML = '';
  2079. const rules = (state.filterRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2080. document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
  2081. if (rules.length === 0) {
  2082. empty?.classList.remove('hidden');
  2083. return;
  2084. }
  2085. empty?.classList.add('hidden');
  2086. rules.forEach((r, idx) => {
  2087. const tr = document.createElement('tr');
  2088. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2089. const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
  2090. const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
  2091. tr.innerHTML = `
  2092. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  2093. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  2094. <td class="py-2.5 px-3 font-bold text-white">${r.chain}</td>
  2095. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  2096. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  2097. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}</td>
  2098. <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
  2099. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  2100. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  2101. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2102. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2103. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2104. </td>
  2105. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2106. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2107. <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2108. <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2109. <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>
  2110. <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2111. <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2112. </td>
  2113. `;
  2114. tbody.appendChild(tr);
  2115. });
  2116. }
  2117. function formatTarget(addr, list, geo) {
  2118. const parts = [];
  2119. if (addr) parts.push(`<span>${addr}</span>`);
  2120. if (list) {
  2121. const inv = list.startsWith('!') ? '!' : '';
  2122. const clean = list.replace(/^!/, '');
  2123. 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>`);
  2124. }
  2125. if (geo) {
  2126. const inv = geo.startsWith('!') ? '!' : '';
  2127. const clean = geo.replace(/^!/, '').replace(/^geo:/, '');
  2128. 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>`);
  2129. }
  2130. if (parts.length === 0) return '<span class="text-slate-600">0.0.0.0/0</span>';
  2131. return parts.join(' ');
  2132. }
  2133. function populateInterfaceSelect(selectId, currentVal = '') {
  2134. const sel = document.getElementById(selectId);
  2135. if (!sel) return;
  2136. sel.innerHTML = '<option value="">(Any Interface)</option>';
  2137. (state.interfaces || []).forEach(i => {
  2138. const opt = document.createElement('option');
  2139. opt.value = i.name;
  2140. opt.innerText = `${i.name} (${i.role || i.type})`;
  2141. if (i.name === currentVal) opt.selected = true;
  2142. sel.appendChild(opt);
  2143. });
  2144. }
  2145. function populateAddressListSelect(selectId, currentVal = '') {
  2146. const sel = document.getElementById(selectId);
  2147. if (!sel) return;
  2148. sel.innerHTML = '<option value="">(None)</option>';
  2149. const cleanVal = (currentVal || '').replace(/^!/, '');
  2150. const customNames = Array.from(new Set((state.addressLists || []).map(a => a.name))).sort();
  2151. customNames.forEach(name => {
  2152. const count = (state.addressLists || []).filter(a => a.name === name).length;
  2153. const opt = document.createElement('option');
  2154. opt.value = name;
  2155. opt.innerText = `${name} (${count} entries)`;
  2156. if (name === cleanVal) opt.selected = true;
  2157. sel.appendChild(opt);
  2158. });
  2159. if (cleanVal && !sel.querySelector(`option[value="${cleanVal}"]`)) {
  2160. const opt = document.createElement('option');
  2161. opt.value = cleanVal;
  2162. opt.innerText = cleanVal;
  2163. opt.selected = true;
  2164. sel.appendChild(opt);
  2165. }
  2166. }
  2167. function populateGeoIPSelect(selectId, currentVal = '') {
  2168. const sel = document.getElementById(selectId);
  2169. if (!sel) return;
  2170. sel.innerHTML = '<option value="">(None)</option>';
  2171. const cleanVal = (currentVal || '').replace(/^!/, '').replace(/^geo:/, '').toUpperCase();
  2172. // Presets optgroup
  2173. const grpPresets = document.createElement('optgroup');
  2174. grpPresets.label = '⚡ Regional Presets';
  2175. const presets = [
  2176. { code: 'EU', label: '🇪🇺 European Union (EU - 27 countries)' },
  2177. { code: 'BALKANS', label: '🏛️ Balkans (GR, CY, BG, RO, AL, etc.)' },
  2178. { code: 'BLOCKLIST', label: '🛡️ High-Risk Blocklist (CN, RU, IR, KP, BY)' }
  2179. ];
  2180. presets.forEach(p => {
  2181. const opt = document.createElement('option');
  2182. opt.value = p.code;
  2183. opt.innerText = p.label;
  2184. if (p.code === cleanVal) opt.selected = true;
  2185. grpPresets.appendChild(opt);
  2186. });
  2187. sel.appendChild(grpPresets);
  2188. // All Countries optgroup
  2189. const grpCountries = document.createElement('optgroup');
  2190. grpCountries.label = '🌍 All Countries';
  2191. const countries = (state.geoCountries || []).slice().sort((a, b) => a.name.localeCompare(b.name));
  2192. countries.forEach(c => {
  2193. const opt = document.createElement('option');
  2194. opt.value = c.code;
  2195. const subnetsInfo = c.subnet_count ? ` [${c.subnet_count.toLocaleString()} subnets]` : '';
  2196. opt.innerText = `${c.name} (${c.code})${subnetsInfo}`;
  2197. if (c.code === cleanVal) opt.selected = true;
  2198. grpCountries.appendChild(opt);
  2199. });
  2200. sel.appendChild(grpCountries);
  2201. }
  2202. function openAddFilterModal() {
  2203. document.getElementById('filter-modal-title').innerText = 'Add Firewall Filter Rule';
  2204. document.getElementById('filter-modal-id').value = '';
  2205. document.getElementById('filter-modal-chain').value = 'forward';
  2206. document.getElementById('filter-modal-action').value = 'accept';
  2207. document.getElementById('filter-modal-proto').value = 'all';
  2208. document.getElementById('filter-modal-src').value = '';
  2209. document.getElementById('filter-modal-dst').value = '';
  2210. document.getElementById('filter-modal-sport').value = '';
  2211. document.getElementById('filter-modal-dport').value = '';
  2212. document.getElementById('filter-modal-connmark').value = '';
  2213. document.getElementById('filter-modal-comment').value = '';
  2214. document.getElementById('filter-modal-disabled').checked = false;
  2215. document.getElementById('filter-modal-cs-established').checked = false;
  2216. document.getElementById('filter-modal-cs-related').checked = false;
  2217. document.getElementById('filter-modal-cs-new').checked = false;
  2218. document.getElementById('filter-modal-cs-invalid').checked = false;
  2219. populateInterfaceSelect('filter-modal-iniface');
  2220. populateInterfaceSelect('filter-modal-outiface');
  2221. if (document.getElementById('filter-modal-srclist-inv')) document.getElementById('filter-modal-srclist-inv').checked = false;
  2222. if (document.getElementById('filter-modal-dstlist-inv')) document.getElementById('filter-modal-dstlist-inv').checked = false;
  2223. populateAddressListSelect('filter-modal-srclist');
  2224. populateAddressListSelect('filter-modal-dstlist');
  2225. if (document.getElementById('filter-modal-srcgeoip-inv')) document.getElementById('filter-modal-srcgeoip-inv').checked = false;
  2226. if (document.getElementById('filter-modal-dstgeoip-inv')) document.getElementById('filter-modal-dstgeoip-inv').checked = false;
  2227. populateGeoIPSelect('filter-modal-srcgeoip');
  2228. populateGeoIPSelect('filter-modal-dstgeoip');
  2229. toggleFilterActionFields();
  2230. document.getElementById('filter-modal').classList.remove('hidden');
  2231. }
  2232. function openEditFilterModal(id) {
  2233. const r = (state.filterRules || []).find(rule => rule.id === id);
  2234. if (!r) return;
  2235. document.getElementById('filter-modal-title').innerText = `Edit Filter Rule (#${r.order})`;
  2236. document.getElementById('filter-modal-id').value = r.id;
  2237. document.getElementById('filter-modal-chain').value = r.chain || 'forward';
  2238. document.getElementById('filter-modal-action').value = r.action || 'accept';
  2239. document.getElementById('filter-modal-proto').value = r.protocol || 'all';
  2240. document.getElementById('filter-modal-src').value = r.src_address || '';
  2241. document.getElementById('filter-modal-dst').value = r.dst_address || '';
  2242. document.getElementById('filter-modal-sport').value = r.src_port || '';
  2243. document.getElementById('filter-modal-dport').value = r.dst_port || '';
  2244. document.getElementById('filter-modal-connmark').value = r.connection_mark || '';
  2245. document.getElementById('filter-modal-comment').value = r.comment || '';
  2246. document.getElementById('filter-modal-disabled').checked = !!r.disabled;
  2247. const states = r.connection_state || [];
  2248. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  2249. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  2250. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  2251. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  2252. populateInterfaceSelect('filter-modal-iniface', r.in_interface);
  2253. populateInterfaceSelect('filter-modal-outiface', r.out_interface);
  2254. const srcInv = (r.src_address_list || '').startsWith('!');
  2255. const dstInv = (r.dst_address_list || '').startsWith('!');
  2256. if (document.getElementById('filter-modal-srclist-inv')) document.getElementById('filter-modal-srclist-inv').checked = srcInv;
  2257. if (document.getElementById('filter-modal-dstlist-inv')) document.getElementById('filter-modal-dstlist-inv').checked = dstInv;
  2258. populateAddressListSelect('filter-modal-srclist', r.src_address_list || '');
  2259. populateAddressListSelect('filter-modal-dstlist', r.dst_address_list || '');
  2260. const srcGeoInv = (r.src_geoip || '').startsWith('!');
  2261. const dstGeoInv = (r.dst_geoip || '').startsWith('!');
  2262. if (document.getElementById('filter-modal-srcgeoip-inv')) document.getElementById('filter-modal-srcgeoip-inv').checked = srcGeoInv;
  2263. if (document.getElementById('filter-modal-dstgeoip-inv')) document.getElementById('filter-modal-dstgeoip-inv').checked = dstGeoInv;
  2264. populateGeoIPSelect('filter-modal-srcgeoip', r.src_geoip || '');
  2265. populateGeoIPSelect('filter-modal-dstgeoip', r.dst_geoip || '');
  2266. toggleFilterActionFields();
  2267. document.getElementById('filter-modal').classList.remove('hidden');
  2268. }
  2269. function closeFilterModal() {
  2270. document.getElementById('filter-modal').classList.add('hidden');
  2271. }
  2272. function toggleFilterActionFields() {
  2273. const act = document.getElementById('filter-modal-action').value;
  2274. const rejectBox = document.getElementById('filter-action-reject-box');
  2275. if (rejectBox) {
  2276. if (act === 'reject') rejectBox.classList.remove('hidden');
  2277. else rejectBox.classList.add('hidden');
  2278. }
  2279. }
  2280. async function submitSaveFilterRule(e) {
  2281. e.preventDefault();
  2282. const id = document.getElementById('filter-modal-id').value;
  2283. const chain = document.getElementById('filter-modal-chain').value;
  2284. const action = document.getElementById('filter-modal-action').value;
  2285. const proto = document.getElementById('filter-modal-proto').value;
  2286. const src = document.getElementById('filter-modal-src').value.trim();
  2287. const dst = document.getElementById('filter-modal-dst').value.trim();
  2288. const sport = document.getElementById('filter-modal-sport').value.trim();
  2289. const dport = document.getElementById('filter-modal-dport').value.trim();
  2290. const inIface = document.getElementById('filter-modal-iniface').value;
  2291. const outIface = document.getElementById('filter-modal-outiface').value;
  2292. const connmark = document.getElementById('filter-modal-connmark').value.trim();
  2293. let srclist = document.getElementById('filter-modal-srclist')?.value || '';
  2294. if (srclist && document.getElementById('filter-modal-srclist-inv')?.checked) {
  2295. srclist = '!' + srclist.replace(/^!/, '');
  2296. }
  2297. let dstlist = document.getElementById('filter-modal-dstlist')?.value || '';
  2298. if (dstlist && document.getElementById('filter-modal-dstlist-inv')?.checked) {
  2299. dstlist = '!' + dstlist.replace(/^!/, '');
  2300. }
  2301. let srcgeoip = document.getElementById('filter-modal-srcgeoip')?.value || '';
  2302. if (srcgeoip && document.getElementById('filter-modal-srcgeoip-inv')?.checked) {
  2303. srcgeoip = '!' + srcgeoip.replace(/^!/, '');
  2304. }
  2305. let dstgeoip = document.getElementById('filter-modal-dstgeoip')?.value || '';
  2306. if (dstgeoip && document.getElementById('filter-modal-dstgeoip-inv')?.checked) {
  2307. dstgeoip = '!' + dstgeoip.replace(/^!/, '');
  2308. }
  2309. const comment = document.getElementById('filter-modal-comment').value.trim();
  2310. const disabled = document.getElementById('filter-modal-disabled').checked;
  2311. const rejectWith = document.getElementById('filter-modal-rejectwith')?.value || '';
  2312. const states = [];
  2313. if (document.getElementById('filter-modal-cs-established').checked) states.push('established');
  2314. if (document.getElementById('filter-modal-cs-related').checked) states.push('related');
  2315. if (document.getElementById('filter-modal-cs-new').checked) states.push('new');
  2316. if (document.getElementById('filter-modal-cs-invalid').checked) states.push('invalid');
  2317. try {
  2318. const res = await fetch(`${API_BASE}/firewall/filter`, {
  2319. method: 'POST',
  2320. headers: { 'Content-Type': 'application/json' },
  2321. body: JSON.stringify({
  2322. id,
  2323. chain,
  2324. action,
  2325. reject_with: rejectWith,
  2326. protocol: proto,
  2327. src_address: src,
  2328. dst_address: dst,
  2329. src_port: sport,
  2330. dst_port: dport,
  2331. in_interface: inIface,
  2332. out_interface: outIface,
  2333. connection_state: states,
  2334. connection_mark: connmark,
  2335. src_address_list: srclist,
  2336. dst_address_list: dstlist,
  2337. src_geoip: srcgeoip,
  2338. dst_geoip: dstgeoip,
  2339. comment,
  2340. disabled
  2341. })
  2342. });
  2343. if (res.ok) {
  2344. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  2345. closeFilterModal();
  2346. loadFirewall(false);
  2347. } else {
  2348. const err = await res.json();
  2349. showToast('Error', err.message, 'error');
  2350. }
  2351. } catch (err) {
  2352. showToast('Error', err.message, 'error');
  2353. }
  2354. }
  2355. async function moveFilterRule(id, dir) {
  2356. try {
  2357. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  2358. method: 'POST',
  2359. headers: { 'Content-Type': 'application/json' },
  2360. body: JSON.stringify({ direction: dir })
  2361. });
  2362. if (res.ok) loadFirewall(false);
  2363. } catch (err) {
  2364. showToast('Error', err.message, 'error');
  2365. }
  2366. }
  2367. async function toggleFilterRuleState(id, disabled) {
  2368. try {
  2369. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  2370. method: 'POST',
  2371. headers: { 'Content-Type': 'application/json' },
  2372. body: JSON.stringify({ disabled })
  2373. });
  2374. if (res.ok) loadFirewall(false);
  2375. } catch (err) {
  2376. showToast('Error', err.message, 'error');
  2377. }
  2378. }
  2379. async function deleteFilterRule(id) {
  2380. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  2381. try {
  2382. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  2383. if (res.ok) {
  2384. showToast('Deleted', 'Filter rule removed', 'success');
  2385. loadFirewall(false);
  2386. }
  2387. } catch (err) {
  2388. showToast('Error', err.message, 'error');
  2389. }
  2390. }
  2391. // ----------------- NAT Rules -----------------
  2392. function renderNATRules() {
  2393. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  2394. const tbody = document.getElementById('nat-table-body');
  2395. const empty = document.getElementById('nat-empty');
  2396. if (!tbody) return;
  2397. tbody.innerHTML = '';
  2398. const rules = (state.natRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2399. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  2400. if (rules.length === 0) {
  2401. empty?.classList.remove('hidden');
  2402. return;
  2403. }
  2404. empty?.classList.add('hidden');
  2405. rules.forEach((r, idx) => {
  2406. const tr = document.createElement('tr');
  2407. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2408. const toTarget = [r.to_addresses, r.to_ports].filter(Boolean).join(':');
  2409. const ifaces = [r.out_interface ? 'out:' + r.out_interface : '', r.in_interface ? 'in:' + r.in_interface : ''].filter(Boolean).join(' ');
  2410. tr.innerHTML = `
  2411. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  2412. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  2413. <td class="py-2.5 px-3 font-bold text-amber-400">${r.chain}</td>
  2414. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  2415. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  2416. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}${r.dst_port ? ':' + r.dst_port : ''}</td>
  2417. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  2418. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  2419. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${toTarget || '-'}</td>
  2420. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2421. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2422. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2423. </td>
  2424. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2425. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2426. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2427. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2428. <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>
  2429. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2430. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2431. </td>
  2432. `;
  2433. tbody.appendChild(tr);
  2434. });
  2435. }
  2436. function openAddNATModal() {
  2437. document.getElementById('nat-modal-title').innerText = 'Add NAT Rule';
  2438. document.getElementById('nat-modal-id').value = '';
  2439. document.getElementById('nat-modal-chain').value = 'srcnat';
  2440. document.getElementById('nat-modal-action').value = 'masquerade';
  2441. document.getElementById('nat-modal-toaddr').value = '';
  2442. document.getElementById('nat-modal-toport').value = '';
  2443. document.getElementById('nat-modal-proto').value = 'all';
  2444. document.getElementById('nat-modal-src').value = '';
  2445. document.getElementById('nat-modal-dst').value = '';
  2446. document.getElementById('nat-modal-dport').value = '';
  2447. document.getElementById('nat-modal-comment').value = '';
  2448. document.getElementById('nat-modal-disabled').checked = false;
  2449. populateInterfaceSelect('nat-modal-iniface');
  2450. populateInterfaceSelect('nat-modal-outiface');
  2451. populateAddressListSelect('nat-modal-srclist');
  2452. populateAddressListSelect('nat-modal-dstlist');
  2453. const srcInvEl = document.getElementById('nat-modal-srclist-inv');
  2454. if (srcInvEl) srcInvEl.checked = false;
  2455. const dstInvEl = document.getElementById('nat-modal-dstlist-inv');
  2456. if (dstInvEl) dstInvEl.checked = false;
  2457. populateGeoIPSelect('nat-modal-srcgeoip');
  2458. populateGeoIPSelect('nat-modal-dstgeoip');
  2459. const srcGeoInvEl = document.getElementById('nat-modal-srcgeoip-inv');
  2460. if (srcGeoInvEl) srcGeoInvEl.checked = false;
  2461. const dstGeoInvEl = document.getElementById('nat-modal-dstgeoip-inv');
  2462. if (dstGeoInvEl) dstGeoInvEl.checked = false;
  2463. toggleNATActionFields();
  2464. document.getElementById('nat-modal').classList.remove('hidden');
  2465. }
  2466. function openEditNATModal(id) {
  2467. const r = (state.natRules || []).find(rule => rule.id === id);
  2468. if (!r) return;
  2469. document.getElementById('nat-modal-title').innerText = `Edit NAT Rule (#${r.order})`;
  2470. document.getElementById('nat-modal-id').value = r.id;
  2471. document.getElementById('nat-modal-chain').value = r.chain || 'srcnat';
  2472. document.getElementById('nat-modal-action').value = r.action || 'masquerade';
  2473. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  2474. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  2475. document.getElementById('nat-modal-proto').value = r.protocol || 'all';
  2476. document.getElementById('nat-modal-src').value = r.src_address || '';
  2477. document.getElementById('nat-modal-dst').value = r.dst_address || '';
  2478. document.getElementById('nat-modal-dport').value = r.dst_port || '';
  2479. document.getElementById('nat-modal-comment').value = r.comment || '';
  2480. document.getElementById('nat-modal-disabled').checked = !!r.disabled;
  2481. populateInterfaceSelect('nat-modal-iniface', r.in_interface);
  2482. populateInterfaceSelect('nat-modal-outiface', r.out_interface);
  2483. const srcInv = (r.src_address_list || '').startsWith('!');
  2484. const dstInv = (r.dst_address_list || '').startsWith('!');
  2485. const srcInvEl = document.getElementById('nat-modal-srclist-inv');
  2486. if (srcInvEl) srcInvEl.checked = srcInv;
  2487. const dstInvEl = document.getElementById('nat-modal-dstlist-inv');
  2488. if (dstInvEl) dstInvEl.checked = dstInv;
  2489. populateAddressListSelect('nat-modal-srclist', r.src_address_list || '');
  2490. populateAddressListSelect('nat-modal-dstlist', r.dst_address_list || '');
  2491. const srcGeoInv = (r.src_geoip || '').startsWith('!');
  2492. const dstGeoInv = (r.dst_geoip || '').startsWith('!');
  2493. const srcGeoInvEl = document.getElementById('nat-modal-srcgeoip-inv');
  2494. if (srcGeoInvEl) srcGeoInvEl.checked = srcGeoInv;
  2495. const dstGeoInvEl = document.getElementById('nat-modal-dstgeoip-inv');
  2496. if (dstGeoInvEl) dstGeoInvEl.checked = dstGeoInv;
  2497. populateGeoIPSelect('nat-modal-srcgeoip', r.src_geoip || '');
  2498. populateGeoIPSelect('nat-modal-dstgeoip', r.dst_geoip || '');
  2499. toggleNATActionFields();
  2500. document.getElementById('nat-modal').classList.remove('hidden');
  2501. }
  2502. function closeNATModal() {
  2503. document.getElementById('nat-modal').classList.add('hidden');
  2504. }
  2505. function toggleNATChainFields() {
  2506. const ch = document.getElementById('nat-modal-chain').value;
  2507. const actSel = document.getElementById('nat-modal-action');
  2508. if (ch === 'srcnat' && actSel.value === 'dst-nat') {
  2509. actSel.value = 'masquerade';
  2510. } else if (ch === 'dstnat' && actSel.value === 'masquerade') {
  2511. actSel.value = 'dst-nat';
  2512. }
  2513. toggleNATActionFields();
  2514. }
  2515. function toggleNATActionFields() {
  2516. const act = document.getElementById('nat-modal-action').value;
  2517. const toBox = document.getElementById('nat-action-to-box');
  2518. if (toBox) {
  2519. if (act === 'masquerade' || act === 'accept') toBox.classList.add('hidden');
  2520. else toBox.classList.remove('hidden');
  2521. }
  2522. }
  2523. async function submitSaveNATRule(e) {
  2524. e.preventDefault();
  2525. const id = document.getElementById('nat-modal-id').value;
  2526. const chain = document.getElementById('nat-modal-chain').value;
  2527. const action = document.getElementById('nat-modal-action').value;
  2528. const toaddr = document.getElementById('nat-modal-toaddr').value.trim();
  2529. const toport = document.getElementById('nat-modal-toport').value.trim();
  2530. const proto = document.getElementById('nat-modal-proto').value;
  2531. const src = document.getElementById('nat-modal-src').value.trim();
  2532. const dst = document.getElementById('nat-modal-dst').value.trim();
  2533. const dport = document.getElementById('nat-modal-dport').value.trim();
  2534. const inIface = document.getElementById('nat-modal-iniface').value;
  2535. const outIface = document.getElementById('nat-modal-outiface').value;
  2536. let srclist = document.getElementById('nat-modal-srclist')?.value || '';
  2537. if (srclist && document.getElementById('nat-modal-srclist-inv')?.checked) {
  2538. srclist = '!' + srclist.replace(/^!/, '');
  2539. }
  2540. let dstlist = document.getElementById('nat-modal-dstlist')?.value || '';
  2541. if (dstlist && document.getElementById('nat-modal-dstlist-inv')?.checked) {
  2542. dstlist = '!' + dstlist.replace(/^!/, '');
  2543. }
  2544. let srcgeoip = document.getElementById('nat-modal-srcgeoip')?.value || '';
  2545. if (srcgeoip && document.getElementById('nat-modal-srcgeoip-inv')?.checked) {
  2546. srcgeoip = '!' + srcgeoip.replace(/^!/, '');
  2547. }
  2548. let dstgeoip = document.getElementById('nat-modal-dstgeoip')?.value || '';
  2549. if (dstgeoip && document.getElementById('nat-modal-dstgeoip-inv')?.checked) {
  2550. dstgeoip = '!' + dstgeoip.replace(/^!/, '');
  2551. }
  2552. const comment = document.getElementById('nat-modal-comment').value.trim();
  2553. const disabled = document.getElementById('nat-modal-disabled').checked;
  2554. try {
  2555. const res = await fetch(`${API_BASE}/firewall/nat`, {
  2556. method: 'POST',
  2557. headers: { 'Content-Type': 'application/json' },
  2558. body: JSON.stringify({
  2559. id,
  2560. chain,
  2561. action,
  2562. to_addresses: toaddr,
  2563. to_ports: toport,
  2564. protocol: proto,
  2565. src_address: src,
  2566. dst_address: dst,
  2567. dst_port: dport,
  2568. in_interface: inIface,
  2569. out_interface: outIface,
  2570. src_address_list: srclist,
  2571. dst_address_list: dstlist,
  2572. src_geoip: srcgeoip,
  2573. dst_geoip: dstgeoip,
  2574. comment,
  2575. disabled
  2576. })
  2577. });
  2578. if (res.ok) {
  2579. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  2580. closeNATModal();
  2581. loadFirewall(false);
  2582. }
  2583. } catch (err) {
  2584. showToast('Error', err.message, 'error');
  2585. }
  2586. }
  2587. async function moveNATRule(id, dir) {
  2588. try {
  2589. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  2590. method: 'POST',
  2591. headers: { 'Content-Type': 'application/json' },
  2592. body: JSON.stringify({ direction: dir })
  2593. });
  2594. if (res.ok) loadFirewall(false);
  2595. } catch (err) {
  2596. showToast('Error', err.message, 'error');
  2597. }
  2598. }
  2599. async function toggleNATRuleState(id, disabled) {
  2600. try {
  2601. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  2602. method: 'POST',
  2603. headers: { 'Content-Type': 'application/json' },
  2604. body: JSON.stringify({ disabled })
  2605. });
  2606. if (res.ok) loadFirewall(false);
  2607. } catch (err) {
  2608. showToast('Error', err.message, 'error');
  2609. }
  2610. }
  2611. async function deleteNATRule(id) {
  2612. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  2613. try {
  2614. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  2615. if (res.ok) {
  2616. showToast('Deleted', 'NAT rule removed', 'success');
  2617. loadFirewall(false);
  2618. }
  2619. } catch (err) {
  2620. showToast('Error', err.message, 'error');
  2621. }
  2622. }
  2623. // ----------------- Mangle Rules -----------------
  2624. function renderMangleRules() {
  2625. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  2626. const tbody = document.getElementById('mangle-table-body');
  2627. const empty = document.getElementById('mangle-empty');
  2628. if (!tbody) return;
  2629. tbody.innerHTML = '';
  2630. const rules = (state.mangleRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2631. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  2632. if (rules.length === 0) {
  2633. empty?.classList.remove('hidden');
  2634. return;
  2635. }
  2636. empty?.classList.add('hidden');
  2637. rules.forEach((r, idx) => {
  2638. const tr = document.createElement('tr');
  2639. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2640. const markVal = r.new_connection_mark || r.new_routing_mark || r.new_packet_mark || r.new_mss || (r.new_dscp ? 'DSCP:' + r.new_dscp : '');
  2641. tr.innerHTML = `
  2642. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  2643. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  2644. <td class="py-2.5 px-3 font-bold text-purple-400">${r.chain}</td>
  2645. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  2646. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  2647. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  2648. <td class="py-2.5 px-3 font-mono font-bold text-cyan-300">${markVal || '-'}</td>
  2649. <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>
  2650. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2651. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2652. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2653. </td>
  2654. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2655. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2656. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2657. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2658. <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>
  2659. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2660. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2661. </td>
  2662. `;
  2663. tbody.appendChild(tr);
  2664. });
  2665. }
  2666. function openAddMangleModal() {
  2667. document.getElementById('mangle-modal-title').innerText = 'Add Mangle Rule';
  2668. document.getElementById('mangle-modal-id').value = '';
  2669. document.getElementById('mangle-modal-chain').value = 'prerouting';
  2670. document.getElementById('mangle-modal-action').value = 'mark-connection';
  2671. document.getElementById('mangle-modal-newmark').value = '';
  2672. document.getElementById('mangle-modal-passthrough').checked = true;
  2673. document.getElementById('mangle-modal-src').value = '';
  2674. document.getElementById('mangle-modal-dst').value = '';
  2675. document.getElementById('mangle-modal-connmark').value = '';
  2676. document.getElementById('mangle-modal-comment').value = '';
  2677. document.getElementById('mangle-modal-disabled').checked = false;
  2678. populateInterfaceSelect('mangle-modal-iniface');
  2679. populateAddressListSelect('mangle-modal-srclist');
  2680. populateAddressListSelect('mangle-modal-dstlist');
  2681. const srcInvEl = document.getElementById('mangle-modal-srclist-inv');
  2682. if (srcInvEl) srcInvEl.checked = false;
  2683. const dstInvEl = document.getElementById('mangle-modal-dstlist-inv');
  2684. if (dstInvEl) dstInvEl.checked = false;
  2685. populateGeoIPSelect('mangle-modal-srcgeoip');
  2686. populateGeoIPSelect('mangle-modal-dstgeoip');
  2687. const srcGeoInvEl = document.getElementById('mangle-modal-srcgeoip-inv');
  2688. if (srcGeoInvEl) srcGeoInvEl.checked = false;
  2689. const dstGeoInvEl = document.getElementById('mangle-modal-dstgeoip-inv');
  2690. if (dstGeoInvEl) dstGeoInvEl.checked = false;
  2691. document.getElementById('mangle-modal').classList.remove('hidden');
  2692. }
  2693. function openEditMangleModal(id) {
  2694. const r = (state.mangleRules || []).find(rule => rule.id === id);
  2695. if (!r) return;
  2696. document.getElementById('mangle-modal-title').innerText = `Edit Mangle Rule (#${r.order})`;
  2697. document.getElementById('mangle-modal-id').value = r.id;
  2698. document.getElementById('mangle-modal-chain').value = r.chain || 'prerouting';
  2699. document.getElementById('mangle-modal-action').value = r.action || 'mark-connection';
  2700. document.getElementById('mangle-modal-newmark').value = r.new_connection_mark || r.new_routing_mark || r.new_packet_mark || r.new_mss || '';
  2701. document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  2702. document.getElementById('mangle-modal-src').value = r.src_address || '';
  2703. document.getElementById('mangle-modal-dst').value = r.dst_address || '';
  2704. document.getElementById('mangle-modal-connmark').value = r.connection_mark || '';
  2705. document.getElementById('mangle-modal-comment').value = r.comment || '';
  2706. document.getElementById('mangle-modal-disabled').checked = !!r.disabled;
  2707. populateInterfaceSelect('mangle-modal-iniface', r.in_interface);
  2708. const srcInv = (r.src_address_list || '').startsWith('!');
  2709. const dstInv = (r.dst_address_list || '').startsWith('!');
  2710. const srcInvEl = document.getElementById('mangle-modal-srclist-inv');
  2711. if (srcInvEl) srcInvEl.checked = srcInv;
  2712. const dstInvEl = document.getElementById('mangle-modal-dstlist-inv');
  2713. if (dstInvEl) dstInvEl.checked = dstInv;
  2714. populateAddressListSelect('mangle-modal-srclist', r.src_address_list || '');
  2715. populateAddressListSelect('mangle-modal-dstlist', r.dst_address_list || '');
  2716. const srcGeoInv = (r.src_geoip || '').startsWith('!');
  2717. const dstGeoInv = (r.dst_geoip || '').startsWith('!');
  2718. const srcGeoInvEl = document.getElementById('mangle-modal-srcgeoip-inv');
  2719. if (srcGeoInvEl) srcGeoInvEl.checked = srcGeoInv;
  2720. const dstGeoInvEl = document.getElementById('mangle-modal-dstgeoip-inv');
  2721. if (dstGeoInvEl) dstGeoInvEl.checked = dstGeoInv;
  2722. populateGeoIPSelect('mangle-modal-srcgeoip', r.src_geoip || '');
  2723. populateGeoIPSelect('mangle-modal-dstgeoip', r.dst_geoip || '');
  2724. document.getElementById('mangle-modal').classList.remove('hidden');
  2725. }
  2726. function closeMangleModal() {
  2727. document.getElementById('mangle-modal').classList.add('hidden');
  2728. }
  2729. function toggleMangleActionFields() {
  2730. // Handled smoothly by single dynamic input
  2731. }
  2732. async function submitSaveMangleRule(e) {
  2733. e.preventDefault();
  2734. const id = document.getElementById('mangle-modal-id').value;
  2735. const chain = document.getElementById('mangle-modal-chain').value;
  2736. const action = document.getElementById('mangle-modal-action').value;
  2737. const newmark = document.getElementById('mangle-modal-newmark').value.trim();
  2738. const passthrough = document.getElementById('mangle-modal-passthrough').checked;
  2739. const src = document.getElementById('mangle-modal-src').value.trim();
  2740. const dst = document.getElementById('mangle-modal-dst').value.trim();
  2741. const inIface = document.getElementById('mangle-modal-iniface').value;
  2742. let srclist = document.getElementById('mangle-modal-srclist')?.value || '';
  2743. if (srclist && document.getElementById('mangle-modal-srclist-inv')?.checked) {
  2744. srclist = '!' + srclist.replace(/^!/, '');
  2745. }
  2746. let dstlist = document.getElementById('mangle-modal-dstlist')?.value || '';
  2747. if (dstlist && document.getElementById('mangle-modal-dstlist-inv')?.checked) {
  2748. dstlist = '!' + dstlist.replace(/^!/, '');
  2749. }
  2750. let srcgeoip = document.getElementById('mangle-modal-srcgeoip')?.value || '';
  2751. if (srcgeoip && document.getElementById('mangle-modal-srcgeoip-inv')?.checked) {
  2752. srcgeoip = '!' + srcgeoip.replace(/^!/, '');
  2753. }
  2754. let dstgeoip = document.getElementById('mangle-modal-dstgeoip')?.value || '';
  2755. if (dstgeoip && document.getElementById('mangle-modal-dstgeoip-inv')?.checked) {
  2756. dstgeoip = '!' + dstgeoip.replace(/^!/, '');
  2757. }
  2758. const connmark = document.getElementById('mangle-modal-connmark').value.trim();
  2759. const comment = document.getElementById('mangle-modal-comment').value.trim();
  2760. const disabled = document.getElementById('mangle-modal-disabled').checked;
  2761. const payload = {
  2762. id,
  2763. chain,
  2764. action,
  2765. passthrough,
  2766. src_address: src,
  2767. dst_address: dst,
  2768. in_interface: inIface,
  2769. src_address_list: srclist,
  2770. dst_address_list: dstlist,
  2771. src_geoip: srcgeoip,
  2772. dst_geoip: dstgeoip,
  2773. connection_mark: connmark,
  2774. comment,
  2775. disabled
  2776. };
  2777. if (action === 'mark-connection') payload.new_connection_mark = newmark;
  2778. else if (action === 'mark-routing') payload.new_routing_mark = newmark;
  2779. else if (action === 'mark-packet') payload.new_packet_mark = newmark;
  2780. else if (action === 'change-mss') payload.new_mss = newmark || 'clamp-to-pmtu';
  2781. try {
  2782. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  2783. method: 'POST',
  2784. headers: { 'Content-Type': 'application/json' },
  2785. body: JSON.stringify(payload)
  2786. });
  2787. if (res.ok) {
  2788. showToast('Mangle Rule Saved', 'Marking rule applied', 'success');
  2789. closeMangleModal();
  2790. loadFirewall(false);
  2791. }
  2792. } catch (err) {
  2793. showToast('Error', err.message, 'error');
  2794. }
  2795. }
  2796. async function moveMangleRule(id, dir) {
  2797. try {
  2798. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  2799. method: 'POST',
  2800. headers: { 'Content-Type': 'application/json' },
  2801. body: JSON.stringify({ direction: dir })
  2802. });
  2803. if (res.ok) loadFirewall(false);
  2804. } catch (err) {
  2805. showToast('Error', err.message, 'error');
  2806. }
  2807. }
  2808. async function toggleMangleRuleState(id, disabled) {
  2809. try {
  2810. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  2811. method: 'POST',
  2812. headers: { 'Content-Type': 'application/json' },
  2813. body: JSON.stringify({ disabled })
  2814. });
  2815. if (res.ok) loadFirewall(false);
  2816. } catch (err) {
  2817. showToast('Error', err.message, 'error');
  2818. }
  2819. }
  2820. async function deleteMangleRule(id) {
  2821. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  2822. try {
  2823. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  2824. if (res.ok) {
  2825. showToast('Deleted', 'Mangle rule removed', 'success');
  2826. loadFirewall(false);
  2827. }
  2828. } catch (err) {
  2829. showToast('Error', err.message, 'error');
  2830. }
  2831. }
  2832. // ----------------- Address Lists -----------------
  2833. function renderAddressLists() {
  2834. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  2835. const tbody = document.getElementById('addrlist-table-body');
  2836. const empty = document.getElementById('addrlist-empty');
  2837. if (!tbody) return;
  2838. tbody.innerHTML = '';
  2839. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  2840. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries`;
  2841. // Update filter select
  2842. const sel = document.getElementById('addrlist-filter-name');
  2843. if (sel) {
  2844. const cur = sel.value;
  2845. sel.innerHTML = '<option value="">All Lists</option>';
  2846. const set = new Set((state.addressLists || []).map(a => a.name));
  2847. set.forEach(n => {
  2848. const opt = document.createElement('option');
  2849. opt.value = n;
  2850. opt.innerText = n;
  2851. if (n === cur) opt.selected = true;
  2852. sel.appendChild(opt);
  2853. });
  2854. }
  2855. if (entries.length === 0) {
  2856. empty?.classList.remove('hidden');
  2857. return;
  2858. }
  2859. empty?.classList.add('hidden');
  2860. entries.forEach((e, idx) => {
  2861. const tr = document.createElement('tr');
  2862. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
  2863. tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
  2864. tr.innerHTML = `
  2865. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  2866. <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>
  2867. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  2868. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  2869. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]">${e.comment || '-'}</td>
  2870. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  2871. <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>
  2872. <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
  2873. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2874. </td>
  2875. `;
  2876. tbody.appendChild(tr);
  2877. });
  2878. }
  2879. function openAddAddrListModal() {
  2880. document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
  2881. document.getElementById('addrlist-modal-id').value = '';
  2882. document.getElementById('addrlist-modal-name').value = '';
  2883. document.getElementById('addrlist-modal-addr').value = '';
  2884. document.getElementById('addrlist-modal-comment').value = '';
  2885. document.getElementById('addrlist-modal-disabled').checked = false;
  2886. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  2887. if (submitBtn) submitBtn.innerText = 'Add to List';
  2888. document.getElementById('addrlist-modal').classList.remove('hidden');
  2889. }
  2890. function openEditAddrListModal(id) {
  2891. const e = (state.addressLists || []).find(item => item.id === id);
  2892. if (!e) return;
  2893. document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
  2894. document.getElementById('addrlist-modal-id').value = e.id;
  2895. document.getElementById('addrlist-modal-name').value = e.name;
  2896. document.getElementById('addrlist-modal-addr').value = e.address;
  2897. document.getElementById('addrlist-modal-comment').value = e.comment || '';
  2898. document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
  2899. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  2900. if (submitBtn) submitBtn.innerText = 'Save Changes';
  2901. document.getElementById('addrlist-modal').classList.remove('hidden');
  2902. }
  2903. function closeAddrListModal() {
  2904. document.getElementById('addrlist-modal').classList.add('hidden');
  2905. }
  2906. async function submitSaveAddrList(e) {
  2907. e.preventDefault();
  2908. const id = document.getElementById('addrlist-modal-id').value;
  2909. const name = document.getElementById('addrlist-modal-name').value.trim();
  2910. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  2911. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  2912. const disabled = document.getElementById('addrlist-modal-disabled').checked;
  2913. try {
  2914. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  2915. method: 'POST',
  2916. headers: { 'Content-Type': 'application/json' },
  2917. body: JSON.stringify({ id, name, address: addr, comment, disabled })
  2918. });
  2919. if (res.ok) {
  2920. showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
  2921. closeAddrListModal();
  2922. loadFirewall(false);
  2923. } else {
  2924. const err = await res.json();
  2925. showToast('Error', err.message || 'Failed to save address list', 'error');
  2926. }
  2927. } catch (err) {
  2928. showToast('Error', err.message, 'error');
  2929. }
  2930. }
  2931. async function toggleAddrListState(id, disabled) {
  2932. try {
  2933. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
  2934. method: 'POST',
  2935. headers: { 'Content-Type': 'application/json' },
  2936. body: JSON.stringify({ disabled })
  2937. });
  2938. if (res.ok) {
  2939. loadFirewall(false);
  2940. }
  2941. } catch (err) {
  2942. showToast('Error', err.message, 'error');
  2943. }
  2944. }
  2945. async function deleteAddrList(id) {
  2946. if (!confirm('Are you sure you want to delete this address list item?')) return;
  2947. try {
  2948. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  2949. if (res.ok) {
  2950. showToast('Deleted', 'Address list item removed', 'info');
  2951. loadFirewall(false);
  2952. }
  2953. } catch (err) {
  2954. showToast('Error', err.message, 'error');
  2955. }
  2956. }
  2957. // ----------------- Geo-Location IP Management -----------------
  2958. async function loadGeoIP() {
  2959. try {
  2960. const [statusRes, countriesRes] = await Promise.all([
  2961. fetch(`${API_BASE}/firewall/geoip/status`),
  2962. fetch(`${API_BASE}/firewall/geoip/countries`)
  2963. ]);
  2964. if (statusRes.ok) state.geoStatus = await statusRes.json();
  2965. if (countriesRes.ok) state.geoCountries = await countriesRes.json();
  2966. updateGeoHeader();
  2967. renderGeoCountries();
  2968. } catch (err) {
  2969. console.error('Failed to load GeoIP:', err);
  2970. }
  2971. }
  2972. function getGeoUsageMap() {
  2973. const usage = {};
  2974. const checkRule = (r, type) => {
  2975. ['src_geoip', 'dst_geoip'].forEach(field => {
  2976. let val = (r && r[field]) || '';
  2977. let code = val.replace(/^!/, '').replace(/^geo:/, '').replace(/^geo_/, '').toUpperCase().trim();
  2978. if (code) {
  2979. if (!usage[code]) usage[code] = [];
  2980. const label = `${type} #${r.priority !== undefined ? r.priority : (r.id || '')}`;
  2981. if (!usage[code].includes(label)) usage[code].push(label);
  2982. }
  2983. });
  2984. };
  2985. (state.filterRules || []).forEach(r => checkRule(r, 'Filter'));
  2986. (state.natRules || []).forEach(r => checkRule(r, 'NAT'));
  2987. (state.mangleRules || []).forEach(r => checkRule(r, 'Mangle'));
  2988. return usage;
  2989. }
  2990. function updateGeoHeader() {
  2991. const s = state.geoStatus || {};
  2992. const statusBadge = document.getElementById('geo-status-badge');
  2993. if (statusBadge) {
  2994. statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
  2995. statusBadge.className = s.auto_update
  2996. ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
  2997. : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
  2998. }
  2999. const intervalLabel = document.getElementById('geo-interval-label');
  3000. if (intervalLabel) {
  3001. intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
  3002. }
  3003. const usageMap = getGeoUsageMap();
  3004. const inUseCount = Object.keys(usageMap).length;
  3005. const activeCountEl = document.getElementById('geo-stat-active-countries');
  3006. if (activeCountEl) activeCountEl.innerText = inUseCount.toLocaleString();
  3007. const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
  3008. if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
  3009. const lastSyncEl = document.getElementById('geo-stat-last-sync');
  3010. if (lastSyncEl) {
  3011. if (s.last_updated && !s.last_updated.startsWith('0001')) {
  3012. const d = new Date(s.last_updated);
  3013. lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  3014. } else {
  3015. lastSyncEl.innerText = 'Never (Sync Pending)';
  3016. }
  3017. }
  3018. const nextSyncEl = document.getElementById('geo-stat-next-sync');
  3019. if (nextSyncEl) {
  3020. if (s.next_update && !s.next_update.startsWith('0001')) {
  3021. const d = new Date(s.next_update);
  3022. nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  3023. } else {
  3024. nextSyncEl.innerText = '-';
  3025. }
  3026. }
  3027. const badge = document.getElementById('fw-badge-geo');
  3028. if (badge) badge.innerText = inUseCount || (state.geoCountries || []).filter(c => c.subnet_count > 0).length || 0;
  3029. }
  3030. function renderGeoCountries() {
  3031. const tbody = document.getElementById('geo-table-body');
  3032. const empty = document.getElementById('geo-empty');
  3033. if (!tbody) return;
  3034. tbody.innerHTML = '';
  3035. const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
  3036. const continent = document.getElementById('geo-continent-filter')?.value || '';
  3037. const inUseOnly = document.getElementById('geo-filter-inuse-only')?.checked;
  3038. const cachedOnly = document.getElementById('geo-filter-cached-only')?.checked;
  3039. const usageMap = getGeoUsageMap();
  3040. const countries = (state.geoCountries || []).filter(c => {
  3041. const isUsed = !!usageMap[c.code];
  3042. if (inUseOnly && !isUsed) return false;
  3043. if (cachedOnly && (!c.subnet_count || c.subnet_count === 0)) return false;
  3044. if (continent && c.continent !== continent) return false;
  3045. if (q) {
  3046. const matchCode = c.code.toLowerCase().includes(q);
  3047. const matchName = c.name.toLowerCase().includes(q);
  3048. if (!matchCode && !matchName) return false;
  3049. }
  3050. return true;
  3051. });
  3052. if (countries.length === 0) {
  3053. empty?.classList.remove('hidden');
  3054. return;
  3055. }
  3056. empty?.classList.add('hidden');
  3057. countries.forEach(c => {
  3058. const tr = document.createElement('tr');
  3059. const isUsed = !!usageMap[c.code];
  3060. const rulesUsing = usageMap[c.code] || [];
  3061. tr.className = `hover:bg-slate-800/40 transition text-xs ${isUsed ? 'bg-emerald-950/20' : ''}`;
  3062. let statusHtml = '';
  3063. if (isUsed) {
  3064. 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>`;
  3065. } else if (c.subnet_count > 0) {
  3066. 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>';
  3067. } else {
  3068. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-slate-500 bg-slate-800/60">READY</span>';
  3069. }
  3070. tr.innerHTML = `
  3071. <td class="py-2.5 px-3 text-center">
  3072. <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'}">
  3073. ${c.code}
  3074. </span>
  3075. </td>
  3076. <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
  3077. <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
  3078. <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
  3079. ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
  3080. </td>
  3081. <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
  3082. <td class="py-2.5 px-3">
  3083. ${statusHtml}
  3084. </td>
  3085. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  3086. <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>
  3087. <button onclick="viewGeoSubnets('${c.code}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
  3088. </td>
  3089. `;
  3090. tbody.appendChild(tr);
  3091. });
  3092. }
  3093. function quickFilterGeo(preset) {
  3094. const searchInput = document.getElementById('geo-search-input');
  3095. const continentSel = document.getElementById('geo-continent-filter');
  3096. const inUseCheck = document.getElementById('geo-filter-inuse-only');
  3097. const cachedCheck = document.getElementById('geo-filter-cached-only');
  3098. if (searchInput) searchInput.value = '';
  3099. if (continentSel) continentSel.value = '';
  3100. if (inUseCheck) inUseCheck.checked = false;
  3101. if (cachedCheck) cachedCheck.checked = false;
  3102. if (preset === 'GR') {
  3103. if (searchInput) searchInput.value = 'Greece';
  3104. } else if (preset === 'Europe') {
  3105. if (continentSel) continentSel.value = 'Europe';
  3106. } else if (preset === 'HIGHRISK') {
  3107. if (searchInput) searchInput.value = 'China';
  3108. }
  3109. renderGeoCountries();
  3110. }
  3111. async function toggleGeoCountry(code, enabled) {
  3112. try {
  3113. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
  3114. method: 'POST',
  3115. headers: { 'Content-Type': 'application/json' },
  3116. body: JSON.stringify({ enabled })
  3117. });
  3118. if (res.ok) {
  3119. showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
  3120. loadGeoIP();
  3121. } else {
  3122. const err = await res.json();
  3123. showToast('Error', err.message || 'Failed to toggle country', 'error');
  3124. }
  3125. } catch (err) {
  3126. showToast('Error', err.message, 'error');
  3127. }
  3128. }
  3129. async function updateGeoCountry(code) {
  3130. try {
  3131. showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
  3132. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
  3133. if (res.ok) {
  3134. const data = await res.json();
  3135. showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
  3136. loadGeoIP();
  3137. } else {
  3138. const err = await res.json();
  3139. showToast('Sync Error', err.message || 'Failed to sync country', 'error');
  3140. }
  3141. } catch (err) {
  3142. showToast('Error', err.message, 'error');
  3143. }
  3144. }
  3145. async function triggerGeoUpdateNow() {
  3146. const spinner = document.getElementById('geo-update-spinner');
  3147. if (spinner) spinner.classList.remove('hidden');
  3148. try {
  3149. const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
  3150. if (res.ok) {
  3151. showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
  3152. setTimeout(() => {
  3153. loadGeoIP();
  3154. if (spinner) spinner.classList.add('hidden');
  3155. }, 2500);
  3156. } else {
  3157. const err = await res.json();
  3158. showToast('Notice', err.message || 'Update in progress', 'info');
  3159. if (spinner) spinner.classList.add('hidden');
  3160. }
  3161. } catch (err) {
  3162. showToast('Error', err.message, 'error');
  3163. if (spinner) spinner.classList.add('hidden');
  3164. }
  3165. }
  3166. async function applyGeoPreset(preset) {
  3167. try {
  3168. const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
  3169. method: 'POST',
  3170. headers: { 'Content-Type': 'application/json' },
  3171. body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
  3172. });
  3173. if (res.ok) {
  3174. showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
  3175. loadGeoIP();
  3176. }
  3177. } catch (err) {
  3178. showToast('Error', err.message, 'error');
  3179. }
  3180. }
  3181. function openGeoIntervalModal() {
  3182. const s = state.geoStatus || {};
  3183. document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
  3184. const sel = document.getElementById('geo-cfg-interval');
  3185. const customBox = document.getElementById('geo-cfg-custom-box');
  3186. const customHoursInput = document.getElementById('geo-cfg-custom-hours');
  3187. const curHours = s.interval_hours || 24;
  3188. const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
  3189. if (matchOption) {
  3190. sel.value = String(curHours);
  3191. customBox.classList.add('hidden');
  3192. } else {
  3193. sel.value = 'custom';
  3194. customHoursInput.value = curHours;
  3195. customBox.classList.remove('hidden');
  3196. }
  3197. document.getElementById('geo-interval-modal').classList.remove('hidden');
  3198. }
  3199. function closeGeoIntervalModal() {
  3200. document.getElementById('geo-interval-modal').classList.add('hidden');
  3201. }
  3202. function toggleCustomGeoInterval() {
  3203. const val = document.getElementById('geo-cfg-interval').value;
  3204. const customBox = document.getElementById('geo-cfg-custom-box');
  3205. if (val === 'custom') {
  3206. customBox.classList.remove('hidden');
  3207. } else {
  3208. customBox.classList.add('hidden');
  3209. }
  3210. }
  3211. async function submitGeoIntervalSettings(e) {
  3212. e.preventDefault();
  3213. const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
  3214. const intervalVal = document.getElementById('geo-cfg-interval').value;
  3215. let hours = 24;
  3216. if (intervalVal === 'custom') {
  3217. hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
  3218. } else {
  3219. hours = parseInt(intervalVal, 10) || 24;
  3220. }
  3221. try {
  3222. const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
  3223. method: 'POST',
  3224. headers: { 'Content-Type': 'application/json' },
  3225. body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
  3226. });
  3227. if (res.ok) {
  3228. showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
  3229. closeGeoIntervalModal();
  3230. loadGeoIP();
  3231. } else {
  3232. const err = await res.json();
  3233. showToast('Error', err.message || 'Failed to save schedule', 'error');
  3234. }
  3235. } catch (err) {
  3236. showToast('Error', err.message, 'error');
  3237. }
  3238. }
  3239. async function viewGeoSubnets(code, name) {
  3240. if (!name) {
  3241. const found = (state.geoCountries || []).find(x => x.code === code);
  3242. name = found ? found.name : code;
  3243. }
  3244. document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
  3245. document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
  3246. const listEl = document.getElementById('geo-subnets-list');
  3247. listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
  3248. document.getElementById('geo-subnets-modal').classList.remove('hidden');
  3249. try {
  3250. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
  3251. if (res.ok) {
  3252. const data = await res.json();
  3253. const subnets = data.subnets || [];
  3254. if (subnets.length === 0) {
  3255. listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
  3256. } else {
  3257. listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
  3258. }
  3259. } else {
  3260. listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
  3261. }
  3262. } catch (err) {
  3263. listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
  3264. }
  3265. }
  3266. function closeGeoSubnetsModal() {
  3267. document.getElementById('geo-subnets-modal').classList.add('hidden');
  3268. }
  3269. // ----------------- Active Connections Tracking -----------------
  3270. async function loadConnections() {
  3271. try {
  3272. const res = await fetch(`${API_BASE}/firewall/connections`);
  3273. const data = await res.json();
  3274. state.connections = Array.isArray(data) ? data : [];
  3275. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  3276. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  3277. renderConnections();
  3278. } catch (err) {
  3279. console.error('Failed to load connections:', err);
  3280. }
  3281. }
  3282. function renderConnections() {
  3283. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  3284. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  3285. const tbody = document.getElementById('conns-table-body');
  3286. const empty = document.getElementById('conns-empty');
  3287. if (!tbody) return;
  3288. tbody.innerHTML = '';
  3289. const conns = (state.connections || []).filter(c => {
  3290. if (protoFilter && c.protocol !== protoFilter) return false;
  3291. if (search) {
  3292. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  3293. if (!line.includes(search)) return false;
  3294. }
  3295. return true;
  3296. });
  3297. if (conns.length === 0) {
  3298. empty?.classList.remove('hidden');
  3299. return;
  3300. }
  3301. empty?.classList.add('hidden');
  3302. conns.slice(0, 150).forEach(c => {
  3303. const tr = document.createElement('tr');
  3304. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  3305. let stateColor = 'text-slate-400';
  3306. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  3307. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  3308. tr.innerHTML = `
  3309. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  3310. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  3311. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  3312. <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>
  3313. <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>
  3314. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  3315. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  3316. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  3317. <td class="py-2.5 px-3 text-right font-sans">
  3318. <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>
  3319. </td>
  3320. `;
  3321. tbody.appendChild(tr);
  3322. });
  3323. }
  3324. async function killConnection(protocol, src, sport, dst, dport) {
  3325. try {
  3326. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  3327. method: 'POST',
  3328. headers: { 'Content-Type': 'application/json' },
  3329. body: JSON.stringify({ protocol, src, sport, dst, dport })
  3330. });
  3331. if (res.ok) {
  3332. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  3333. loadConnections();
  3334. }
  3335. } catch (err) {
  3336. showToast('Error', err.message, 'error');
  3337. }
  3338. }
  3339. async function resetFirewallCounters() {
  3340. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  3341. try {
  3342. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  3343. if (res.ok) {
  3344. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  3345. loadFirewall(false);
  3346. }
  3347. } catch (err) {
  3348. showToast('Error', err.message, 'error');
  3349. }
  3350. }
  3351. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  3352. function switchRoutesSubTab(tab) {
  3353. state.routesSubTab = tab;
  3354. const tabs = ['routes', 'rules', 'tables'];
  3355. tabs.forEach(t => {
  3356. const panel = document.getElementById(`routes-subtab-${t}`);
  3357. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  3358. if (panel) {
  3359. if (t === tab) panel.classList.remove('hidden');
  3360. else panel.classList.add('hidden');
  3361. }
  3362. if (btn) {
  3363. if (t === tab) {
  3364. 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';
  3365. } else {
  3366. 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';
  3367. }
  3368. }
  3369. });
  3370. }
  3371. async function loadRoutes() {
  3372. try {
  3373. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  3374. fetch(`${API_BASE}/routes`),
  3375. fetch(`${API_BASE}/routing/rules`),
  3376. fetch(`${API_BASE}/routing/tables`)
  3377. ]);
  3378. if (routesRes.ok) state.routes = await routesRes.json();
  3379. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  3380. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  3381. const bRoutes = document.getElementById('routes-badge-routes');
  3382. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  3383. const bRules = document.getElementById('routes-badge-rules');
  3384. if (bRules) bRules.innerText = (state.policyRules || []).length;
  3385. const bTables = document.getElementById('routes-badge-tables');
  3386. if (bTables) bTables.innerText = (state.routingTables || []).length;
  3387. const bRoutesCount = document.getElementById('badge-routes-count');
  3388. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  3389. renderRoutesList();
  3390. renderPolicyRules();
  3391. renderRoutingTables();
  3392. } catch (err) {
  3393. console.error('Failed to load routing:', err);
  3394. }
  3395. }
  3396. function renderRoutesList() {
  3397. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  3398. const tbody = document.getElementById('routes-table-body');
  3399. const empty = document.getElementById('routes-empty');
  3400. if (!tbody) return;
  3401. tbody.innerHTML = '';
  3402. // Update table filter select
  3403. const sel = document.getElementById('routes-filter-table');
  3404. if (sel) {
  3405. const cur = sel.value;
  3406. sel.innerHTML = '<option value="">All Tables</option>';
  3407. (state.routingTables || []).forEach(t => {
  3408. const opt = document.createElement('option');
  3409. opt.value = t.name;
  3410. opt.innerText = t.name;
  3411. if (t.name === cur) opt.selected = true;
  3412. sel.appendChild(opt);
  3413. });
  3414. }
  3415. const routes = (state.routes || []).filter(r => !tableFilter || r.routing_table === tableFilter);
  3416. document.getElementById('routes-count-badge').innerText = `${routes.length} Routes`;
  3417. if (routes.length === 0) {
  3418. empty?.classList.remove('hidden');
  3419. return;
  3420. }
  3421. empty?.classList.add('hidden');
  3422. routes.forEach(r => {
  3423. const tr = document.createElement('tr');
  3424. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  3425. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  3426. // MikroTik Flags string: D=Dynamic, A=Active, C=Connect, S=Static, X=Disabled
  3427. let flags = '';
  3428. if (r.dynamic) flags += 'D';
  3429. if (r.active) flags += 'A';
  3430. if (r.connect) flags += 'C';
  3431. if (r.static) flags += 'S';
  3432. if (r.disabled) flags += 'X';
  3433. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  3434. tr.innerHTML = `
  3435. <td class="py-2.5 px-3 text-center">
  3436. <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'}">
  3437. ${flags || '-'}
  3438. </span>
  3439. </td>
  3440. <td class="py-2.5 px-3 font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${r.dst_address}</td>
  3441. <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>
  3442. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  3443. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  3444. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  3445. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  3446. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  3447. ${r.static ? `
  3448. <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>
  3449. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  3450. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3451. ` : `
  3452. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  3453. `}
  3454. </td>
  3455. `;
  3456. tbody.appendChild(tr);
  3457. });
  3458. }
  3459. function openAddRouteModal() {
  3460. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  3461. document.getElementById('route-modal-id').value = '';
  3462. document.getElementById('route-modal-old-dst').value = '';
  3463. document.getElementById('route-modal-old-gw').value = '';
  3464. document.getElementById('route-modal-old-distance').value = '';
  3465. document.getElementById('route-modal-old-table').value = '';
  3466. document.getElementById('route-modal-old-iface').value = '';
  3467. const dstInput = document.getElementById('route-modal-dst');
  3468. const gwInput = document.getElementById('route-modal-gw');
  3469. const distInput = document.getElementById('route-modal-distance');
  3470. const ifaceSelect = document.getElementById('route-modal-iface');
  3471. const tableSelect = document.getElementById('route-modal-table');
  3472. const commentInput = document.getElementById('route-modal-comment');
  3473. const disCheck = document.getElementById('route-modal-disabled');
  3474. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  3475. dstInput.disabled = false;
  3476. dstInput.value = '0.0.0.0/0';
  3477. gwInput.disabled = false;
  3478. gwInput.value = '';
  3479. distInput.disabled = false;
  3480. distInput.value = '1';
  3481. ifaceSelect.disabled = false;
  3482. tableSelect.disabled = false;
  3483. commentInput.disabled = false;
  3484. commentInput.value = '';
  3485. disCheck.disabled = false;
  3486. disCheck.checked = false;
  3487. if (saveBtn) saveBtn.classList.remove('hidden');
  3488. populateInterfaceSelect('route-modal-iface');
  3489. // Populate tables
  3490. tableSelect.innerHTML = '';
  3491. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  3492. const opt = document.createElement('option');
  3493. opt.value = t.name;
  3494. opt.innerText = t.name;
  3495. if (t.name === 'main') opt.selected = true;
  3496. tableSelect.appendChild(opt);
  3497. });
  3498. document.getElementById('route-modal').classList.remove('hidden');
  3499. }
  3500. function openEditRouteModal(id) {
  3501. const r = (state.routes || []).find(route => route.id === id);
  3502. if (!r) return;
  3503. const isStatic = !!r.static;
  3504. document.getElementById('route-modal-title').innerText = isStatic
  3505. ? `Edit Route: ${r.dst_address}`
  3506. : `Route Properties (Read Only): ${r.dst_address}`;
  3507. document.getElementById('route-modal-id').value = r.id;
  3508. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  3509. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  3510. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  3511. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  3512. document.getElementById('route-modal-old-iface').value = r.interface || '';
  3513. const dstInput = document.getElementById('route-modal-dst');
  3514. const gwInput = document.getElementById('route-modal-gw');
  3515. const distInput = document.getElementById('route-modal-distance');
  3516. const ifaceSelect = document.getElementById('route-modal-iface');
  3517. const tableSelect = document.getElementById('route-modal-table');
  3518. const commentInput = document.getElementById('route-modal-comment');
  3519. const disCheck = document.getElementById('route-modal-disabled');
  3520. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  3521. dstInput.value = r.dst_address;
  3522. gwInput.value = r.gateway || '';
  3523. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  3524. commentInput.value = r.comment || '';
  3525. disCheck.checked = !!r.disabled;
  3526. dstInput.disabled = !isStatic;
  3527. gwInput.disabled = !isStatic;
  3528. distInput.disabled = !isStatic;
  3529. ifaceSelect.disabled = !isStatic;
  3530. tableSelect.disabled = !isStatic;
  3531. commentInput.disabled = !isStatic;
  3532. disCheck.disabled = !isStatic;
  3533. if (saveBtn) {
  3534. if (isStatic) {
  3535. saveBtn.classList.remove('hidden');
  3536. } else {
  3537. saveBtn.classList.add('hidden');
  3538. }
  3539. }
  3540. populateInterfaceSelect('route-modal-iface', r.interface);
  3541. tableSelect.innerHTML = '';
  3542. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  3543. const opt = document.createElement('option');
  3544. opt.value = t.name;
  3545. opt.innerText = t.name;
  3546. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  3547. tableSelect.appendChild(opt);
  3548. });
  3549. document.getElementById('route-modal').classList.remove('hidden');
  3550. }
  3551. function closeRouteModal() {
  3552. document.getElementById('route-modal').classList.add('hidden');
  3553. }
  3554. async function submitSaveRoute(e) {
  3555. e.preventDefault();
  3556. const id = document.getElementById('route-modal-id').value;
  3557. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  3558. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  3559. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  3560. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  3561. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  3562. const dst = document.getElementById('route-modal-dst').value.trim();
  3563. const gw = document.getElementById('route-modal-gw').value.trim();
  3564. const table = document.getElementById('route-modal-table').value;
  3565. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  3566. const iface = document.getElementById('route-modal-iface').value;
  3567. const comment = document.getElementById('route-modal-comment').value.trim();
  3568. const disabled = document.getElementById('route-modal-disabled').checked;
  3569. if (!dst) {
  3570. showToast('Error', 'Destination address is required', 'error');
  3571. return;
  3572. }
  3573. if (!gw && !iface) {
  3574. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  3575. return;
  3576. }
  3577. const payload = {
  3578. id,
  3579. old_dst_address: oldDst,
  3580. old_gateway: oldGw,
  3581. old_routing_table: oldTable,
  3582. old_interface: oldIface,
  3583. dst_address: dst,
  3584. gateway: gw || iface,
  3585. routing_table: table,
  3586. distance,
  3587. interface: iface,
  3588. comment,
  3589. disabled
  3590. };
  3591. if (oldDistStr !== undefined && oldDistStr !== '') {
  3592. payload.old_distance = parseInt(oldDistStr, 10);
  3593. }
  3594. try {
  3595. const res = await fetch(`${API_BASE}/routes`, {
  3596. method: 'POST',
  3597. headers: { 'Content-Type': 'application/json' },
  3598. body: JSON.stringify(payload)
  3599. });
  3600. if (res.ok) {
  3601. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  3602. closeRouteModal();
  3603. loadRoutes();
  3604. } else {
  3605. const err = await res.json();
  3606. showToast('Error', err.message || 'Failed to save route', 'error');
  3607. }
  3608. } catch (err) {
  3609. showToast('Error', err.message, 'error');
  3610. }
  3611. }
  3612. async function toggleRouteState(id, disabled) {
  3613. try {
  3614. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  3615. method: 'POST',
  3616. headers: { 'Content-Type': 'application/json' },
  3617. body: JSON.stringify({ disabled })
  3618. });
  3619. if (res.ok) loadRoutes();
  3620. } catch (err) {
  3621. showToast('Error', err.message, 'error');
  3622. }
  3623. }
  3624. async function deleteRoute(id) {
  3625. if (!confirm('Are you sure you want to delete this route?')) return;
  3626. try {
  3627. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3628. if (res.ok) {
  3629. showToast('Deleted', 'Route removed', 'success');
  3630. loadRoutes();
  3631. }
  3632. } catch (err) {
  3633. showToast('Error', err.message, 'error');
  3634. }
  3635. }
  3636. // ----------------- Policy Rules (/ip route rule) -----------------
  3637. function renderPolicyRules() {
  3638. const tbody = document.getElementById('rules-table-body');
  3639. const empty = document.getElementById('rules-empty');
  3640. if (!tbody) return;
  3641. tbody.innerHTML = '';
  3642. const rules = state.policyRules || [];
  3643. document.getElementById('rules-count-badge').innerText = `${rules.length} Rules`;
  3644. if (rules.length === 0) {
  3645. empty?.classList.remove('hidden');
  3646. return;
  3647. }
  3648. empty?.classList.add('hidden');
  3649. rules.forEach(pr => {
  3650. const tr = document.createElement('tr');
  3651. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  3652. tr.innerHTML = `
  3653. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  3654. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  3655. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  3656. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  3657. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  3658. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  3659. <td class="py-2.5 px-3 text-right font-sans">
  3660. ${pr.priority < 32766 && pr.priority > 0 ? `
  3661. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3662. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  3663. </td>
  3664. `;
  3665. tbody.appendChild(tr);
  3666. });
  3667. }
  3668. function openAddPolicyRuleModal() {
  3669. document.getElementById('prule-modal-pref').value = (state.policyRules || []).length * 10 + 1000;
  3670. document.getElementById('prule-modal-mark').value = '';
  3671. document.getElementById('prule-modal-src').value = '';
  3672. document.getElementById('prule-modal-dst').value = '';
  3673. const sel = document.getElementById('prule-modal-table');
  3674. sel.innerHTML = '';
  3675. (state.routingTables || []).forEach(t => {
  3676. const opt = document.createElement('option');
  3677. opt.value = t.name;
  3678. opt.innerText = t.name;
  3679. sel.appendChild(opt);
  3680. });
  3681. document.getElementById('prule-modal').classList.remove('hidden');
  3682. }
  3683. function closePolicyRuleModal() {
  3684. document.getElementById('prule-modal').classList.add('hidden');
  3685. }
  3686. async function submitSavePolicyRule(e) {
  3687. e.preventDefault();
  3688. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  3689. const mark = document.getElementById('prule-modal-mark').value.trim();
  3690. const src = document.getElementById('prule-modal-src').value.trim();
  3691. const dst = document.getElementById('prule-modal-dst').value.trim();
  3692. const table = document.getElementById('prule-modal-table').value;
  3693. const action = document.getElementById('prule-modal-action').value;
  3694. try {
  3695. const res = await fetch(`${API_BASE}/routing/rules`, {
  3696. method: 'POST',
  3697. headers: { 'Content-Type': 'application/json' },
  3698. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  3699. });
  3700. if (res.ok) {
  3701. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  3702. closePolicyRuleModal();
  3703. loadRoutes();
  3704. } else {
  3705. const err = await res.json();
  3706. showToast('Error', err.message, 'error');
  3707. }
  3708. } catch (err) {
  3709. showToast('Error', err.message, 'error');
  3710. }
  3711. }
  3712. async function deletePolicyRule(id) {
  3713. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  3714. try {
  3715. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3716. if (res.ok) {
  3717. showToast('Rule Removed', 'Policy rule deleted', 'success');
  3718. loadRoutes();
  3719. }
  3720. } catch (err) {
  3721. showToast('Error', err.message, 'error');
  3722. }
  3723. }
  3724. // ----------------- Routing Tables -----------------
  3725. function renderRoutingTables() {
  3726. const tbody = document.getElementById('tables-table-body');
  3727. if (!tbody) return;
  3728. tbody.innerHTML = '';
  3729. (state.routingTables || []).forEach(t => {
  3730. const tr = document.createElement('tr');
  3731. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  3732. tr.innerHTML = `
  3733. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  3734. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  3735. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  3736. `;
  3737. tbody.appendChild(tr);
  3738. });
  3739. }
  3740. function openAddTableModal() {
  3741. document.getElementById('table-modal-name').value = '';
  3742. document.getElementById('table-modal-id').value = '';
  3743. document.getElementById('table-modal-comment').value = '';
  3744. document.getElementById('table-modal').classList.remove('hidden');
  3745. }
  3746. function closeTableModal() {
  3747. document.getElementById('table-modal').classList.add('hidden');
  3748. }
  3749. async function submitSaveTable(e) {
  3750. e.preventDefault();
  3751. const name = document.getElementById('table-modal-name').value.trim();
  3752. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  3753. const comment = document.getElementById('table-modal-comment').value.trim();
  3754. try {
  3755. const res = await fetch(`${API_BASE}/routing/tables`, {
  3756. method: 'POST',
  3757. headers: { 'Content-Type': 'application/json' },
  3758. body: JSON.stringify({ name, table_id: id, comment })
  3759. });
  3760. if (res.ok) {
  3761. showToast('Table Created', `Routing table ${name} registered`, 'success');
  3762. closeTableModal();
  3763. loadRoutes();
  3764. } else {
  3765. const err = await res.json();
  3766. showToast('Error', err.message, 'error');
  3767. }
  3768. } catch (err) {
  3769. showToast('Error', err.message, 'error');
  3770. }
  3771. }
  3772. async function loadDebianConfig() {
  3773. const view = document.getElementById('debian-config-view');
  3774. view.innerText = 'Generating live configuration...';
  3775. try {
  3776. const res = await fetch(`${API_BASE}/debian/config`);
  3777. const data = await res.json();
  3778. view.innerText = data.content || '# Empty config';
  3779. } catch (err) {
  3780. view.innerText = 'Failed to generate Debian network config.';
  3781. }
  3782. }
  3783. async function saveDebianConfig() {
  3784. try {
  3785. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  3786. const data = await res.json();
  3787. if (res.ok) {
  3788. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  3789. loadDebianConfig();
  3790. }
  3791. } catch (err) {
  3792. showToast('Error', err.message, 'error');
  3793. }
  3794. }
  3795. function showToast(title, message, type = 'info') {
  3796. const container = document.getElementById('toast-container');
  3797. const toast = document.createElement('div');
  3798. const borderColors = {
  3799. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  3800. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  3801. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  3802. };
  3803. 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}`;
  3804. toast.innerHTML = `
  3805. <div class="flex-1">
  3806. <div class="font-bold text-xs text-white">${title}</div>
  3807. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${message}</div>
  3808. </div>
  3809. `;
  3810. container.appendChild(toast);
  3811. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  3812. setTimeout(() => {
  3813. toast.classList.add('opacity-0', 'translate-y-2');
  3814. setTimeout(() => toast.remove(), 300);
  3815. }, 4000);
  3816. }
  3817. function formatTraffic(bytesPerSec) {
  3818. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  3819. const kb = bytesPerSec / 1024;
  3820. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  3821. const mb = kb / 1024;
  3822. return `${mb.toFixed(2)} MB/s`;
  3823. }
  3824. function toggleSidebar() {
  3825. const sb = document.getElementById('sidebar');
  3826. sb.classList.toggle('-translate-x-full');
  3827. }
  3828. // ======================== EoIP (Ethernet over IP) ========================
  3829. async function loadEoIP(populate = true) {
  3830. try {
  3831. const res = await fetch(`${API_BASE}/vpn/eoip`);
  3832. const data = await res.json();
  3833. state.eoipTunnels = Array.isArray(data) ? data : [];
  3834. const badge = document.getElementById('eoip-count-badge');
  3835. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  3836. const sideBadge = document.getElementById('badge-eoip-count');
  3837. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  3838. renderEoIPTunnels();
  3839. } catch (err) {
  3840. console.error('Failed to load EoIP:', err);
  3841. }
  3842. }
  3843. function renderEoIPTunnels() {
  3844. const tbody = document.getElementById('eoip-table-body');
  3845. const empty = document.getElementById('eoip-empty');
  3846. if (!tbody) return;
  3847. tbody.innerHTML = '';
  3848. const tunnels = state.eoipTunnels || [];
  3849. if (tunnels.length === 0) {
  3850. empty?.classList.remove('hidden');
  3851. return;
  3852. }
  3853. empty?.classList.add('hidden');
  3854. tunnels.forEach(t => {
  3855. const tr = document.createElement('tr');
  3856. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  3857. tr.innerHTML = `
  3858. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  3859. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  3860. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  3861. <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>
  3862. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  3863. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  3864. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  3865. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  3866. <td class="py-2.5 px-3 font-mono text-[11px]">
  3867. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  3868. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  3869. </td>
  3870. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  3871. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3872. <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>
  3873. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3874. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  3875. </td>
  3876. `;
  3877. tbody.appendChild(tr);
  3878. });
  3879. }
  3880. function openAddEoIPModal() {
  3881. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  3882. document.getElementById('eoip-modal-id').value = '';
  3883. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  3884. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  3885. document.getElementById('eoip-modal-remote').value = '';
  3886. document.getElementById('eoip-modal-ip').value = '';
  3887. document.getElementById('eoip-modal-local').value = '';
  3888. document.getElementById('eoip-modal-mac').value = '';
  3889. document.getElementById('eoip-modal-mtu').value = '1500';
  3890. document.getElementById('eoip-modal-comment').value = '';
  3891. document.getElementById('eoip-modal-clampmss').checked = true;
  3892. document.getElementById('eoip-modal-disabled').checked = false;
  3893. document.getElementById('eoip-modal').classList.remove('hidden');
  3894. }
  3895. function openEditEoIPModal(id) {
  3896. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  3897. if (!t) return;
  3898. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  3899. document.getElementById('eoip-modal-id').value = t.id;
  3900. document.getElementById('eoip-modal-name').value = t.name;
  3901. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  3902. document.getElementById('eoip-modal-remote').value = t.remote_address;
  3903. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  3904. document.getElementById('eoip-modal-local').value = t.local_address || '';
  3905. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  3906. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  3907. document.getElementById('eoip-modal-comment').value = t.comment || '';
  3908. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  3909. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  3910. document.getElementById('eoip-modal').classList.remove('hidden');
  3911. }
  3912. function closeEoIPModal() {
  3913. document.getElementById('eoip-modal').classList.add('hidden');
  3914. }
  3915. async function submitSaveEoIP(e) {
  3916. e.preventDefault();
  3917. const id = document.getElementById('eoip-modal-id').value;
  3918. const name = document.getElementById('eoip-modal-name').value.trim();
  3919. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  3920. const remote = document.getElementById('eoip-modal-remote').value.trim();
  3921. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  3922. const local = document.getElementById('eoip-modal-local').value.trim();
  3923. const mac = document.getElementById('eoip-modal-mac').value.trim();
  3924. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  3925. const comment = document.getElementById('eoip-modal-comment').value.trim();
  3926. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  3927. const disabled = document.getElementById('eoip-modal-disabled').checked;
  3928. try {
  3929. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  3930. method: 'POST',
  3931. headers: { 'Content-Type': 'application/json' },
  3932. body: JSON.stringify({
  3933. id,
  3934. name,
  3935. tunnel_id: tunnelId,
  3936. remote_address: remote,
  3937. ip_address: ipAddress,
  3938. local_address: local,
  3939. mac_address: mac,
  3940. mtu,
  3941. clamp_mss: clampMss,
  3942. comment,
  3943. disabled
  3944. })
  3945. });
  3946. if (res.ok) {
  3947. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  3948. closeEoIPModal();
  3949. loadEoIP(false);
  3950. fetchData(false);
  3951. } else {
  3952. const err = await res.json();
  3953. showToast('Error', err.message, 'error');
  3954. }
  3955. } catch (err) {
  3956. showToast('Error', err.message, 'error');
  3957. }
  3958. }
  3959. async function toggleEoIPState(id, disabled) {
  3960. try {
  3961. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  3962. method: 'POST',
  3963. headers: { 'Content-Type': 'application/json' },
  3964. body: JSON.stringify({ disabled })
  3965. });
  3966. if (res.ok) {
  3967. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  3968. loadEoIP(false);
  3969. fetchData(false);
  3970. }
  3971. } catch (err) {
  3972. showToast('Error', err.message, 'error');
  3973. }
  3974. }
  3975. async function deleteEoIP(id) {
  3976. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  3977. try {
  3978. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3979. if (res.ok) {
  3980. showToast('Deleted', 'EoIP tunnel removed', 'success');
  3981. loadEoIP(false);
  3982. fetchData(false);
  3983. }
  3984. } catch (err) {
  3985. showToast('Error', err.message, 'error');
  3986. }
  3987. }
  3988. // ======================== PPP Central Hub & Servers ========================
  3989. function switchPPPSubTab(tab) {
  3990. state.pppSubTab = tab;
  3991. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  3992. tabs.forEach(t => {
  3993. const panel = document.getElementById(`ppp-subtab-${t}`);
  3994. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  3995. if (panel) {
  3996. if (t === tab) panel.classList.remove('hidden');
  3997. else panel.classList.add('hidden');
  3998. }
  3999. if (btn) {
  4000. if (t === tab) {
  4001. 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';
  4002. } else {
  4003. 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';
  4004. }
  4005. }
  4006. });
  4007. const addBtn = document.getElementById('ppp-primary-add-btn');
  4008. if (addBtn) {
  4009. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  4010. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  4011. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  4012. else addBtn.innerHTML = '<span>Save Config</span>';
  4013. }
  4014. if (tab === 'active') loadPPPSessions();
  4015. }
  4016. function openCurrentPPPModal() {
  4017. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  4018. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  4019. else if (state.pppSubTab === 'active') loadPPPSessions();
  4020. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  4021. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  4022. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  4023. }
  4024. async function loadPPP(populateDropdowns = true) {
  4025. await Promise.all([
  4026. loadPPPSecrets(),
  4027. loadPPPProfiles(),
  4028. loadPPPServers(),
  4029. loadPPPSessions()
  4030. ]);
  4031. }
  4032. async function loadPPPSecrets() {
  4033. try {
  4034. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  4035. const data = await res.json();
  4036. state.pppSecrets = Array.isArray(data) ? data : [];
  4037. const b = document.getElementById('ppp-badge-secrets');
  4038. if (b) b.innerText = state.pppSecrets.length;
  4039. const b2 = document.getElementById('secrets-count-badge');
  4040. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  4041. renderPPPSecrets();
  4042. } catch (err) {
  4043. console.error('Failed to load PPP secrets:', err);
  4044. }
  4045. }
  4046. function renderPPPSecrets() {
  4047. const tbody = document.getElementById('secrets-table-body');
  4048. const empty = document.getElementById('secrets-empty');
  4049. if (!tbody) return;
  4050. tbody.innerHTML = '';
  4051. const secrets = state.pppSecrets || [];
  4052. if (secrets.length === 0) {
  4053. empty?.classList.remove('hidden');
  4054. return;
  4055. }
  4056. empty?.classList.add('hidden');
  4057. secrets.forEach(s => {
  4058. const tr = document.createElement('tr');
  4059. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  4060. tr.innerHTML = `
  4061. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  4062. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  4063. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  4064. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  4065. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  4066. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  4067. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  4068. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4069. <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>
  4070. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4071. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  4072. </td>
  4073. `;
  4074. tbody.appendChild(tr);
  4075. });
  4076. }
  4077. async function loadPPPProfiles() {
  4078. try {
  4079. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  4080. const data = await res.json();
  4081. state.pppProfiles = Array.isArray(data) ? data : [];
  4082. const b = document.getElementById('ppp-badge-profiles');
  4083. if (b) b.innerText = state.pppProfiles.length;
  4084. const b2 = document.getElementById('profiles-count-badge');
  4085. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  4086. // Populate profile selects across modals
  4087. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  4088. selects.forEach(sid => {
  4089. const el = document.getElementById(sid);
  4090. if (!el) return;
  4091. const cur = el.value;
  4092. el.innerHTML = '';
  4093. state.pppProfiles.forEach(p => {
  4094. const opt = document.createElement('option');
  4095. opt.value = p.name;
  4096. opt.innerText = `${p.name} (${p.remote_address})`;
  4097. if (p.name === cur) opt.selected = true;
  4098. el.appendChild(opt);
  4099. });
  4100. });
  4101. renderPPPProfiles();
  4102. } catch (err) {
  4103. console.error('Failed to load PPP profiles:', err);
  4104. }
  4105. }
  4106. function renderPPPProfiles() {
  4107. const tbody = document.getElementById('profiles-table-body');
  4108. if (!tbody) return;
  4109. tbody.innerHTML = '';
  4110. (state.pppProfiles || []).forEach(p => {
  4111. const isDefault = p.name.startsWith('default');
  4112. const tr = document.createElement('tr');
  4113. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  4114. tr.innerHTML = `
  4115. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  4116. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  4117. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  4118. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  4119. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  4120. <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>
  4121. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  4122. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  4123. ${!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>`}
  4124. </td>
  4125. `;
  4126. tbody.appendChild(tr);
  4127. });
  4128. }
  4129. async function loadPPPServers() {
  4130. try {
  4131. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  4132. fetch(`${API_BASE}/vpn/servers/pppoe`),
  4133. fetch(`${API_BASE}/vpn/servers/pptp`),
  4134. fetch(`${API_BASE}/vpn/servers/l2tp`),
  4135. fetch(`${API_BASE}/vpn/servers/ipsec`)
  4136. ]);
  4137. if (pppoeRes.ok) {
  4138. state.pppoeServer = await pppoeRes.json();
  4139. const s = state.pppoeServer;
  4140. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  4141. document.getElementById('pppoe-server-name').value = s.service_name || 'proxmox-pppoe';
  4142. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  4143. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  4144. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  4145. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  4146. const pill = document.getElementById('pppoe-server-status-pill');
  4147. if (pill) {
  4148. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  4149. 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';
  4150. }
  4151. setDotBadge('ppp-badge-pppoe-state', s.running);
  4152. }
  4153. if (pptpRes.ok) {
  4154. state.pptpServer = await pptpRes.json();
  4155. const s = state.pptpServer;
  4156. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  4157. document.getElementById('pptp-server-port').value = s.port || 1723;
  4158. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  4159. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  4160. const pill = document.getElementById('pptp-server-status-pill');
  4161. if (pill) {
  4162. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  4163. 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';
  4164. }
  4165. setDotBadge('ppp-badge-pptp-state', s.running);
  4166. }
  4167. if (l2tpRes.ok) {
  4168. state.l2tpServer = await l2tpRes.json();
  4169. const s = state.l2tpServer;
  4170. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  4171. document.getElementById('l2tp-server-port').value = s.port || 1701;
  4172. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  4173. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  4174. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  4175. const pill = document.getElementById('l2tp-server-status-pill');
  4176. if (pill) {
  4177. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  4178. 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';
  4179. }
  4180. setDotBadge('ppp-badge-l2tp-state', s.running);
  4181. }
  4182. if (ipsecRes.ok) {
  4183. state.ipsecServer = await ipsecRes.json();
  4184. const s = state.ipsecServer;
  4185. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  4186. if (modalEn) modalEn.checked = !!s.enabled;
  4187. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  4188. if (modalPsk) modalPsk.value = s.preshared_key || '';
  4189. const modalPool = document.getElementById('modal-ipsec-server-pool');
  4190. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  4191. const modalDns = document.getElementById('modal-ipsec-server-dns');
  4192. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  4193. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  4194. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  4195. const pill = document.getElementById('modal-ipsec-server-status');
  4196. if (pill) {
  4197. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  4198. 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';
  4199. }
  4200. }
  4201. } catch (err) {
  4202. console.error('Failed to load VPN servers:', err);
  4203. }
  4204. }
  4205. async function loadPPPSessions() {
  4206. try {
  4207. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  4208. const data = await res.json();
  4209. state.pppActiveSessions = Array.isArray(data) ? data : [];
  4210. const b = document.getElementById('ppp-badge-active');
  4211. if (b) b.innerText = state.pppActiveSessions.length;
  4212. const sideB = document.getElementById('badge-ppp-sessions');
  4213. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  4214. renderPPPSessions();
  4215. } catch (err) {
  4216. console.error('Failed to load active PPP sessions:', err);
  4217. }
  4218. }
  4219. function renderPPPSessions() {
  4220. const tbody = document.getElementById('active-ppp-table-body');
  4221. const empty = document.getElementById('active-ppp-empty');
  4222. if (!tbody) return;
  4223. tbody.innerHTML = '';
  4224. const list = state.pppActiveSessions || [];
  4225. if (list.length === 0) {
  4226. empty?.classList.remove('hidden');
  4227. return;
  4228. }
  4229. empty?.classList.add('hidden');
  4230. list.forEach(s => {
  4231. const tr = document.createElement('tr');
  4232. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  4233. tr.innerHTML = `
  4234. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  4235. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  4236. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  4237. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  4238. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  4239. <td class="py-2.5 px-3 text-[11px]">
  4240. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  4241. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  4242. </td>
  4243. <td class="py-2.5 px-3 text-right font-sans">
  4244. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  4245. </td>
  4246. `;
  4247. tbody.appendChild(tr);
  4248. });
  4249. }
  4250. async function disconnectPPPSession(iface) {
  4251. if (!confirm(`Disconnect session ${iface}?`)) return;
  4252. try {
  4253. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  4254. if (res.ok) {
  4255. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  4256. loadPPPSessions();
  4257. }
  4258. } catch (err) {
  4259. showToast('Error', err.message, 'error');
  4260. }
  4261. }
  4262. // PPP Secret Modal handlers
  4263. function openAddPPPSecretModal() {
  4264. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  4265. document.getElementById('secret-modal-id').value = '';
  4266. document.getElementById('secret-modal-name').value = '';
  4267. document.getElementById('secret-modal-password').value = '';
  4268. document.getElementById('secret-modal-service').value = 'any';
  4269. document.getElementById('secret-modal-profile').value = 'default';
  4270. document.getElementById('secret-modal-local').value = '';
  4271. document.getElementById('secret-modal-remote').value = '';
  4272. document.getElementById('secret-modal-comment').value = '';
  4273. document.getElementById('secret-modal-disabled').checked = false;
  4274. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  4275. }
  4276. function openEditPPPSecretModal(id) {
  4277. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  4278. if (!s) return;
  4279. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  4280. document.getElementById('secret-modal-id').value = s.id;
  4281. document.getElementById('secret-modal-name').value = s.name;
  4282. document.getElementById('secret-modal-password').value = s.password;
  4283. document.getElementById('secret-modal-service').value = s.service || 'any';
  4284. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  4285. document.getElementById('secret-modal-local').value = s.local_address || '';
  4286. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  4287. document.getElementById('secret-modal-comment').value = s.comment || '';
  4288. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  4289. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  4290. }
  4291. function closePPPSecretModal() {
  4292. document.getElementById('ppp-secret-modal').classList.add('hidden');
  4293. }
  4294. async function submitSavePPPSecret(e) {
  4295. e.preventDefault();
  4296. const id = document.getElementById('secret-modal-id').value;
  4297. const name = document.getElementById('secret-modal-name').value.trim();
  4298. const password = document.getElementById('secret-modal-password').value.trim();
  4299. const service = document.getElementById('secret-modal-service').value;
  4300. const profile = document.getElementById('secret-modal-profile').value;
  4301. const local = document.getElementById('secret-modal-local').value.trim();
  4302. const remote = document.getElementById('secret-modal-remote').value.trim();
  4303. const comment = document.getElementById('secret-modal-comment').value.trim();
  4304. const disabled = document.getElementById('secret-modal-disabled').checked;
  4305. try {
  4306. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  4307. method: 'POST',
  4308. headers: { 'Content-Type': 'application/json' },
  4309. body: JSON.stringify({
  4310. id,
  4311. name,
  4312. password,
  4313. service,
  4314. profile,
  4315. local_address: local,
  4316. remote_address: remote,
  4317. comment,
  4318. disabled
  4319. })
  4320. });
  4321. if (res.ok) {
  4322. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  4323. closePPPSecretModal();
  4324. loadPPPSecrets();
  4325. } else {
  4326. const err = await res.json();
  4327. showToast('Error', err.message, 'error');
  4328. }
  4329. } catch (err) {
  4330. showToast('Error', err.message, 'error');
  4331. }
  4332. }
  4333. async function togglePPPSecretState(id, disabled) {
  4334. try {
  4335. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  4336. method: 'POST',
  4337. headers: { 'Content-Type': 'application/json' },
  4338. body: JSON.stringify({ disabled })
  4339. });
  4340. if (res.ok) {
  4341. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  4342. loadPPPSecrets();
  4343. }
  4344. } catch (err) {
  4345. showToast('Error', err.message, 'error');
  4346. }
  4347. }
  4348. async function deletePPPSecret(id) {
  4349. if (!confirm('Are you sure you want to delete this secret account?')) return;
  4350. try {
  4351. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4352. if (res.ok) {
  4353. showToast('Deleted', 'Secret account removed', 'success');
  4354. loadPPPSecrets();
  4355. }
  4356. } catch (err) {
  4357. showToast('Error', err.message, 'error');
  4358. }
  4359. }
  4360. // PPP Profile Modal handlers
  4361. function openAddPPPProfileModal() {
  4362. document.getElementById('profile-modal-name').value = '';
  4363. document.getElementById('profile-modal-local').value = '10.10.10.1';
  4364. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  4365. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  4366. document.getElementById('profile-modal-encryption').value = 'required';
  4367. document.getElementById('profile-modal-onlyone').checked = true;
  4368. document.getElementById('profile-modal-comment').value = '';
  4369. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  4370. }
  4371. function closePPPProfileModal() {
  4372. document.getElementById('ppp-profile-modal').classList.add('hidden');
  4373. }
  4374. async function submitSavePPPProfile(e) {
  4375. e.preventDefault();
  4376. const name = document.getElementById('profile-modal-name').value.trim();
  4377. const local = document.getElementById('profile-modal-local').value.trim();
  4378. const remote = document.getElementById('profile-modal-remote').value.trim();
  4379. const dns = document.getElementById('profile-modal-dns').value.trim();
  4380. const enc = document.getElementById('profile-modal-encryption').value;
  4381. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  4382. const comment = document.getElementById('profile-modal-comment').value.trim();
  4383. try {
  4384. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  4385. method: 'POST',
  4386. headers: { 'Content-Type': 'application/json' },
  4387. body: JSON.stringify({
  4388. id: name,
  4389. name,
  4390. local_address: local,
  4391. remote_address: remote,
  4392. dns_servers: dns,
  4393. use_encryption: enc,
  4394. only_one: onlyone,
  4395. comment
  4396. })
  4397. });
  4398. if (res.ok) {
  4399. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  4400. closePPPProfileModal();
  4401. loadPPPProfiles();
  4402. } else {
  4403. const err = await res.json();
  4404. showToast('Error', err.message, 'error');
  4405. }
  4406. } catch (err) {
  4407. showToast('Error', err.message, 'error');
  4408. }
  4409. }
  4410. async function deletePPPProfile(name) {
  4411. if (!confirm(`Delete PPP profile ${name}?`)) return;
  4412. try {
  4413. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  4414. if (res.ok) {
  4415. showToast('Deleted', 'Profile removed', 'success');
  4416. loadPPPProfiles();
  4417. } else {
  4418. const err = await res.json();
  4419. showToast('Error', err.message, 'error');
  4420. }
  4421. } catch (err) {
  4422. showToast('Error', err.message, 'error');
  4423. }
  4424. }
  4425. // Server Config submissions
  4426. async function savePPPoEServerConfig(e) {
  4427. e.preventDefault();
  4428. const enabled = document.getElementById('pppoe-server-enabled').checked;
  4429. const name = document.getElementById('pppoe-server-name').value.trim();
  4430. const iface = document.getElementById('pppoe-server-iface').value;
  4431. const profile = document.getElementById('pppoe-server-profile').value;
  4432. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  4433. const onesession = document.getElementById('pppoe-server-onesession').checked;
  4434. try {
  4435. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  4436. method: 'POST',
  4437. headers: { 'Content-Type': 'application/json' },
  4438. body: JSON.stringify({
  4439. enabled,
  4440. service_name: name,
  4441. interface: iface,
  4442. default_profile: profile,
  4443. max_mtu: mtu,
  4444. max_mru: mtu,
  4445. one_session_per_host: onesession
  4446. })
  4447. });
  4448. if (res.ok) {
  4449. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  4450. loadPPPServers();
  4451. fetchData(false);
  4452. } else {
  4453. const err = await res.json();
  4454. showToast('Error', err.message, 'error');
  4455. }
  4456. } catch (err) {
  4457. showToast('Error', err.message, 'error');
  4458. }
  4459. }
  4460. async function savePPTPServerConfig(e) {
  4461. e.preventDefault();
  4462. const enabled = document.getElementById('pptp-server-enabled').checked;
  4463. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  4464. const profile = document.getElementById('pptp-server-profile').value;
  4465. const mppe = document.getElementById('pptp-server-mppe').checked;
  4466. try {
  4467. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  4468. method: 'POST',
  4469. headers: { 'Content-Type': 'application/json' },
  4470. body: JSON.stringify({
  4471. enabled,
  4472. port,
  4473. default_profile: profile,
  4474. require_mppe: mppe
  4475. })
  4476. });
  4477. if (res.ok) {
  4478. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  4479. loadPPPServers();
  4480. fetchData(false);
  4481. } else {
  4482. const err = await res.json();
  4483. showToast('Error', err.message, 'error');
  4484. }
  4485. } catch (err) {
  4486. showToast('Error', err.message, 'error');
  4487. }
  4488. }
  4489. async function saveL2TPServerConfig(e) {
  4490. e.preventDefault();
  4491. const enabled = document.getElementById('l2tp-server-enabled').checked;
  4492. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  4493. const profile = document.getElementById('l2tp-server-profile').value;
  4494. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  4495. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  4496. try {
  4497. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  4498. method: 'POST',
  4499. headers: { 'Content-Type': 'application/json' },
  4500. body: JSON.stringify({
  4501. enabled,
  4502. port,
  4503. default_profile: profile,
  4504. use_ipsec: useipsec,
  4505. ipsec_secret: psk
  4506. })
  4507. });
  4508. if (res.ok) {
  4509. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  4510. loadPPPServers();
  4511. fetchData(false);
  4512. } else {
  4513. const err = await res.json();
  4514. showToast('Error', err.message, 'error');
  4515. }
  4516. } catch (err) {
  4517. showToast('Error', err.message, 'error');
  4518. }
  4519. }
  4520. // IPSec Server Modal
  4521. function openIPSecServerModal() {
  4522. loadPPPServers();
  4523. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  4524. }
  4525. function closeIPSecServerModal() {
  4526. document.getElementById('ipsec-server-modal').classList.add('hidden');
  4527. }
  4528. async function submitSaveIPSecServer(e) {
  4529. e.preventDefault();
  4530. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  4531. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  4532. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  4533. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  4534. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  4535. try {
  4536. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  4537. method: 'POST',
  4538. headers: { 'Content-Type': 'application/json' },
  4539. body: JSON.stringify({
  4540. enabled,
  4541. preshared_key: psk,
  4542. pool_address: pool,
  4543. dns_servers: dns,
  4544. local_subnet: subnet
  4545. })
  4546. });
  4547. if (res.ok) {
  4548. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  4549. closeIPSecServerModal();
  4550. loadPPPServers();
  4551. fetchData(false);
  4552. } else {
  4553. const err = await res.json();
  4554. showToast('Error', err.message, 'error');
  4555. }
  4556. } catch (err) {
  4557. showToast('Error', err.message, 'error');
  4558. }
  4559. }
  4560. // WireGuard Client Config Viewer
  4561. let currentWGClientConf = '';
  4562. async function openWGClientConfModal(iface, clientIP) {
  4563. try {
  4564. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  4565. method: 'POST',
  4566. headers: { 'Content-Type': 'application/json' },
  4567. body: JSON.stringify({
  4568. interface: iface,
  4569. address: clientIP || '10.10.0.2/32',
  4570. dns: '1.1.1.1, 8.8.8.8'
  4571. })
  4572. });
  4573. if (res.ok) {
  4574. const data = await res.json();
  4575. currentWGClientConf = data.config;
  4576. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  4577. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  4578. } else {
  4579. const err = await res.json();
  4580. showToast('Error', err.message, 'error');
  4581. }
  4582. } catch (err) {
  4583. showToast('Error', err.message, 'error');
  4584. }
  4585. }
  4586. function closeWGClientConfModal() {
  4587. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  4588. }
  4589. function copyWGClientConf() {
  4590. if (!currentWGClientConf) return;
  4591. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  4592. }
  4593. function downloadWGClientConf() {
  4594. if (!currentWGClientConf) return;
  4595. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  4596. const a = document.createElement('a');
  4597. a.href = URL.createObjectURL(blob);
  4598. a.download = 'wireguard-client.conf';
  4599. document.body.appendChild(a);
  4600. a.click();
  4601. document.body.removeChild(a);
  4602. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  4603. }
  4604. // =========================================================================
  4605. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  4606. // =========================================================================
  4607. state.activeDynSubTab = 'bgp-peers';
  4608. state.activeBgpSubTab = 'bgp-peers';
  4609. state.activeOspfSubTab = 'ospf-ifaces';
  4610. state.bgpInstance = null;
  4611. state.bgpPeers = [];
  4612. state.bgpNets = [];
  4613. state.bgpRoutes = [];
  4614. state.ospfInstance = null;
  4615. state.ospfInterfaces = [];
  4616. state.ospfAreas = [];
  4617. state.ospfNeighbors = [];
  4618. state.ospfRoutes = [];
  4619. function switchBgpSubTab(subTab) {
  4620. state.activeBgpSubTab = subTab;
  4621. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes'];
  4622. tabs.forEach(t => {
  4623. const el = document.getElementById(`dyn-subtab-${t}`);
  4624. const btn = document.getElementById(`bgp-subtab-btn-${t}`);
  4625. if (el) el.classList.toggle('hidden', t !== subTab);
  4626. if (btn) {
  4627. if (t === subTab) {
  4628. 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';
  4629. } else {
  4630. 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';
  4631. }
  4632. }
  4633. });
  4634. }
  4635. function switchOspfSubTab(subTab) {
  4636. state.activeOspfSubTab = subTab;
  4637. const tabs = ['ospf-ifaces', 'ospf-areas', 'ospf-nbrs', 'ospf-routes'];
  4638. tabs.forEach(t => {
  4639. const el = document.getElementById(`dyn-subtab-${t}`);
  4640. const btn = document.getElementById(`ospf-subtab-btn-${t}`);
  4641. if (el) el.classList.toggle('hidden', t !== subTab);
  4642. if (btn) {
  4643. if (t === subTab) {
  4644. 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';
  4645. } else {
  4646. 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';
  4647. }
  4648. }
  4649. });
  4650. }
  4651. function switchDynSubTab(subTab) {
  4652. if (subTab.startsWith('bgp')) {
  4653. if (state.activeTab !== 'bgp') navigate('bgp');
  4654. switchBgpSubTab(subTab);
  4655. } else if (subTab.startsWith('ospf')) {
  4656. if (state.activeTab !== 'ospf') navigate('ospf');
  4657. switchOspfSubTab(subTab);
  4658. }
  4659. }
  4660. async function loadDynamicRouting(showToastMsg = false) {
  4661. try {
  4662. const [sumRes, bgpInstRes, bgpPeersRes, bgpNetsRes, bgpRoutesRes, ospfInstRes, ospfIfacesRes, ospfAreasRes, ospfNbrsRes, ospfRoutesRes, filtersRes] = await Promise.all([
  4663. fetch(`${API_BASE}/routing/dynamic/summary`),
  4664. fetch(`${API_BASE}/routing/bgp/instance`),
  4665. fetch(`${API_BASE}/routing/bgp/peers`),
  4666. fetch(`${API_BASE}/routing/bgp/networks`),
  4667. fetch(`${API_BASE}/routing/bgp/routes`),
  4668. fetch(`${API_BASE}/routing/ospf/instance`),
  4669. fetch(`${API_BASE}/routing/ospf/interfaces`),
  4670. fetch(`${API_BASE}/routing/ospf/areas`),
  4671. fetch(`${API_BASE}/routing/ospf/neighbors`),
  4672. fetch(`${API_BASE}/routing/ospf/routes`),
  4673. fetch(`${API_BASE}/routing/filters`)
  4674. ]);
  4675. if (sumRes.ok) state.dynSummary = await sumRes.json();
  4676. if (bgpInstRes.ok) state.bgpInstance = await bgpInstRes.json();
  4677. if (bgpPeersRes.ok) state.bgpPeers = await bgpPeersRes.json();
  4678. if (bgpNetsRes.ok) state.bgpNets = await bgpNetsRes.json();
  4679. if (bgpRoutesRes.ok) state.bgpRoutes = await bgpRoutesRes.json();
  4680. if (ospfInstRes.ok) state.ospfInstance = await ospfInstRes.json();
  4681. if (ospfIfacesRes.ok) state.ospfInterfaces = await ospfIfacesRes.json();
  4682. if (ospfAreasRes.ok) state.ospfAreas = await ospfAreasRes.json();
  4683. if (ospfNbrsRes.ok) state.ospfNeighbors = await ospfNbrsRes.json();
  4684. if (ospfRoutesRes.ok) state.ospfRoutes = await ospfRoutesRes.json();
  4685. if (filtersRes && filtersRes.ok) state.routingFilters = await filtersRes.json();
  4686. try { renderBgpStatusPill(); } catch(e) { console.error('renderBgpStatusPill error:', e); }
  4687. try { renderBgpPeers(); } catch(e) { console.error('renderBgpPeers error:', e); }
  4688. try { renderBgpNetworks(); } catch(e) { console.error('renderBgpNetworks error:', e); }
  4689. try { renderBgpRoutes(); } catch(e) { console.error('renderBgpRoutes error:', e); }
  4690. try { renderOspfStatusPill(); } catch(e) { console.error('renderOspfStatusPill error:', e); }
  4691. try { renderOspfInterfaces(); } catch(e) { console.error('renderOspfInterfaces error:', e); }
  4692. try { renderOspfAreas(); } catch(e) { console.error('renderOspfAreas error:', e); }
  4693. try { renderOspfNeighbors(); } catch(e) { console.error('renderOspfNeighbors error:', e); }
  4694. try { renderOspfRoutes(); } catch(e) { console.error('renderOspfRoutes error:', e); }
  4695. try { renderRoutingFilters(); } catch(e) { console.error('renderRoutingFilters error:', e); }
  4696. try { updateBadges(); } catch(e) { console.error('updateBadges error:', e); }
  4697. if (showToastMsg) showToast('Refreshed', 'Dynamic routing telemetry updated', 'info');
  4698. } catch (err) {
  4699. console.error('Failed to load dynamic routing:', err);
  4700. if (showToastMsg) showToast('Error', 'Failed to load dynamic routing telemetry', 'error');
  4701. }
  4702. }
  4703. function renderBgpStatusPill() {
  4704. const pill = document.getElementById('bgp-live-status-pill');
  4705. if (!pill) return;
  4706. const inst = state.bgpInstance;
  4707. if (!inst || !inst.enabled) {
  4708. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  4709. pill.innerText = 'BGP DISABLED';
  4710. } else if (inst.running) {
  4711. 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';
  4712. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  4713. } else {
  4714. 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';
  4715. pill.innerText = 'BGP STARTING...';
  4716. }
  4717. }
  4718. function renderBgpPeers() {
  4719. const tbody = document.getElementById('bgp-peers-table-body');
  4720. if (!tbody) return;
  4721. const empty = document.getElementById('bgp-peers-empty');
  4722. const countBadge = document.getElementById('bgp-peers-count-badge');
  4723. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  4724. const peers = state.bgpPeers || [];
  4725. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  4726. if (navBadge) navBadge.innerText = peers.length;
  4727. if (peers.length === 0) {
  4728. tbody.innerHTML = '';
  4729. if (empty) empty.classList.remove('hidden');
  4730. return;
  4731. }
  4732. if (empty) empty.classList.add('hidden');
  4733. tbody.innerHTML = peers.map(p => {
  4734. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  4735. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  4736. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  4737. let stateBadge = '';
  4738. if (p.disabled) {
  4739. 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>';
  4740. } else if (p.state === 'Established') {
  4741. 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>';
  4742. } else if (p.state === 'Connect' || p.state === 'Active') {
  4743. 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>`;
  4744. } else {
  4745. 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>`;
  4746. }
  4747. return `
  4748. <tr class="hover:bg-slate-800/40 transition">
  4749. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  4750. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  4751. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  4752. <td class="py-2.5 px-3 font-bold text-slate-200">AS ${p.remote_as}</td>
  4753. <td class="py-2.5 px-3">${stateBadge}</td>
  4754. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  4755. <td class="py-2.5 px-3 text-slate-300">
  4756. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  4757. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  4758. </td>
  4759. <td class="py-2.5 px-3 font-mono text-[11px] whitespace-nowrap">
  4760. ${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> ` : ''}
  4761. ${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>` : ''}
  4762. ${!p.in_filter && !p.out_filter ? '<span class="text-slate-600">-</span>' : ''}
  4763. </td>
  4764. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  4765. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  4766. <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'}">
  4767. ${p.disabled ? 'Enable' : 'Disable'}
  4768. </button>
  4769. <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">
  4770. Edit
  4771. </button>
  4772. <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">
  4773. Delete
  4774. </button>
  4775. </td>
  4776. </tr>
  4777. `;
  4778. }).join('');
  4779. }
  4780. function renderBgpNetworks() {
  4781. const tbody = document.getElementById('bgp-nets-table-body');
  4782. if (!tbody) return;
  4783. const empty = document.getElementById('bgp-nets-empty');
  4784. const countBadge = document.getElementById('bgp-nets-count-badge');
  4785. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  4786. const nets = state.bgpNets || [];
  4787. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  4788. if (navBadge) navBadge.innerText = nets.length;
  4789. if (nets.length === 0) {
  4790. tbody.innerHTML = '';
  4791. if (empty) empty.classList.remove('hidden');
  4792. return;
  4793. }
  4794. if (empty) empty.classList.add('hidden');
  4795. tbody.innerHTML = nets.map(n => `
  4796. <tr class="hover:bg-slate-800/40 transition">
  4797. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  4798. <td class="py-2.5 px-3">
  4799. ${n.disabled
  4800. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  4801. : '<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>'}
  4802. </td>
  4803. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  4804. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  4805. <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">
  4806. Delete
  4807. </button>
  4808. </td>
  4809. </tr>
  4810. `).join('');
  4811. }
  4812. function renderBgpRoutes() {
  4813. const tbody = document.getElementById('bgp-routes-table-body');
  4814. if (!tbody) return;
  4815. const empty = document.getElementById('bgp-routes-empty');
  4816. const countBadge = document.getElementById('bgp-routes-count-badge');
  4817. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  4818. const routes = state.bgpRoutes || [];
  4819. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  4820. if (navBadge) navBadge.innerText = routes.length;
  4821. if (routes.length === 0) {
  4822. tbody.innerHTML = '';
  4823. if (empty) empty.classList.remove('hidden');
  4824. return;
  4825. }
  4826. if (empty) empty.classList.add('hidden');
  4827. tbody.innerHTML = routes.map(r => `
  4828. <tr class="hover:bg-slate-800/40 transition">
  4829. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  4830. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  4831. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  4832. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  4833. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  4834. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  4835. </tr>
  4836. `).join('');
  4837. }
  4838. function renderOspfStatusPill() {
  4839. const pill = document.getElementById('ospf-live-status-pill');
  4840. if (!pill) return;
  4841. const inst = state.ospfInstance;
  4842. if (!inst || !inst.enabled) {
  4843. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  4844. pill.innerText = 'OSPF DISABLED';
  4845. } else if (inst.running) {
  4846. 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';
  4847. pill.innerText = `OSPF ACTIVE (ID: ${inst.router_id || 'Auto'})`;
  4848. } else {
  4849. 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';
  4850. pill.innerText = 'OSPF STARTING...';
  4851. }
  4852. }
  4853. function renderOspfInterfaces() {
  4854. const tbody = document.getElementById('ospf-ifaces-table-body');
  4855. if (!tbody) return;
  4856. const empty = document.getElementById('ospf-ifaces-empty');
  4857. const countBadge = document.getElementById('ospf-ifaces-count-badge');
  4858. const navBadge = document.getElementById('dyn-badge-ospf-ifaces');
  4859. const ifaces = state.ospfInterfaces || [];
  4860. if (countBadge) countBadge.innerText = `${ifaces.length} Interfaces`;
  4861. if (navBadge) navBadge.innerText = ifaces.length;
  4862. if (ifaces.length === 0) {
  4863. tbody.innerHTML = '';
  4864. if (empty) empty.classList.remove('hidden');
  4865. return;
  4866. }
  4867. if (empty) empty.classList.add('hidden');
  4868. tbody.innerHTML = ifaces.map(i => {
  4869. let flagA = !i.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  4870. let flagP = i.passive ? '<span class="text-amber-400 font-bold ml-1" title="Passive">P</span>' : '';
  4871. let flagX = i.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  4872. return `
  4873. <tr class="hover:bg-slate-800/40 transition">
  4874. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagP}${flagX}</td>
  4875. <td class="py-2.5 px-3 font-semibold text-white font-mono">${escapeHtml(i.network)}</td>
  4876. <td class="py-2.5 px-3 text-indigo-300 font-bold">Area ${escapeHtml(i.area)}</td>
  4877. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(i.interface || 'Any')}</td>
  4878. <td class="py-2.5 px-3 text-slate-300">${i.cost}</td>
  4879. <td class="py-2.5 px-3 text-slate-300">${i.priority}</td>
  4880. <td class="py-2.5 px-3 text-slate-400">${i.hello_interval}s / ${i.dead_interval}s</td>
  4881. <td class="py-2.5 px-3 text-slate-300 uppercase">${escapeHtml(i.auth_type || 'none')}</td>
  4882. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(i.comment || '')}</td>
  4883. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  4884. <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'}">
  4885. ${i.disabled ? 'Enable' : 'Disable'}
  4886. </button>
  4887. <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">
  4888. Edit
  4889. </button>
  4890. <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">
  4891. Delete
  4892. </button>
  4893. </td>
  4894. </tr>
  4895. `;
  4896. }).join('');
  4897. }
  4898. function renderOspfAreas() {
  4899. const tbody = document.getElementById('ospf-areas-table-body');
  4900. if (!tbody) return;
  4901. const countBadge = document.getElementById('ospf-areas-count-badge');
  4902. const navBadge = document.getElementById('dyn-badge-ospf-areas');
  4903. const areas = state.ospfAreas || [];
  4904. if (countBadge) countBadge.innerText = `${areas.length} Areas`;
  4905. if (navBadge) navBadge.innerText = areas.length;
  4906. tbody.innerHTML = areas.map(a => `
  4907. <tr class="hover:bg-slate-800/40 transition">
  4908. <td class="py-2.5 px-3 font-semibold text-white font-mono">${escapeHtml(a.name)}</td>
  4909. <td class="py-2.5 px-3 font-bold text-indigo-300">${escapeHtml(a.area_id)}</td>
  4910. <td class="py-2.5 px-3 text-slate-300 uppercase">${escapeHtml(a.area_type || 'default')}</td>
  4911. <td class="py-2.5 px-3 text-slate-400 font-sans">${escapeHtml(a.comment || '')}</td>
  4912. <td class="py-2.5 px-3 text-right font-sans">
  4913. <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">
  4914. Delete
  4915. </button>
  4916. </td>
  4917. </tr>
  4918. `).join('');
  4919. }
  4920. function renderOspfNeighbors() {
  4921. const tbody = document.getElementById('ospf-nbrs-table-body');
  4922. if (!tbody) return;
  4923. const empty = document.getElementById('ospf-nbrs-empty');
  4924. const countBadge = document.getElementById('ospf-nbrs-count-badge');
  4925. const navBadge = document.getElementById('dyn-badge-ospf-nbrs');
  4926. const nbrs = state.ospfNeighbors || [];
  4927. if (countBadge) countBadge.innerText = `${nbrs.length} Neighbors`;
  4928. if (navBadge) navBadge.innerText = nbrs.length;
  4929. if (nbrs.length === 0) {
  4930. tbody.innerHTML = '';
  4931. if (empty) empty.classList.remove('hidden');
  4932. return;
  4933. }
  4934. if (empty) empty.classList.add('hidden');
  4935. tbody.innerHTML = nbrs.map(n => {
  4936. let stateBadge = '';
  4937. if (n.state && (n.state.startsWith('Full') || n.state.includes('DR') || n.state.includes('Backup'))) {
  4938. 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>`;
  4939. } else {
  4940. 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>`;
  4941. }
  4942. return `
  4943. <tr class="hover:bg-slate-800/40 transition">
  4944. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(n.neighbor_id)}</td>
  4945. <td class="py-2.5 px-3 text-indigo-300 font-bold">${escapeHtml(n.address)}</td>
  4946. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(n.interface)}</td>
  4947. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(n.area || '0.0.0.0')}</td>
  4948. <td class="py-2.5 px-3">${stateBadge}</td>
  4949. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(n.dead_timer || '-')}</td>
  4950. </tr>
  4951. `;
  4952. }).join('');
  4953. }
  4954. function renderOspfRoutes() {
  4955. const tbody = document.getElementById('ospf-routes-table-body');
  4956. if (!tbody) return;
  4957. const empty = document.getElementById('ospf-routes-empty');
  4958. const countBadge = document.getElementById('ospf-routes-count-badge');
  4959. const navBadge = document.getElementById('dyn-badge-ospf-routes');
  4960. const routes = state.ospfRoutes || [];
  4961. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  4962. if (navBadge) navBadge.innerText = routes.length;
  4963. if (routes.length === 0) {
  4964. tbody.innerHTML = '';
  4965. if (empty) empty.classList.remove('hidden');
  4966. return;
  4967. }
  4968. if (empty) empty.classList.add('hidden');
  4969. tbody.innerHTML = routes.map(r => `
  4970. <tr class="hover:bg-slate-800/40 transition">
  4971. <td class="py-2.5 px-3 font-semibold text-white font-mono">${escapeHtml(r.prefix)}</td>
  4972. <td class="py-2.5 px-3 text-slate-300">${escapeHtml(r.route_type || 'Network')}</td>
  4973. <td class="py-2.5 px-3 text-slate-300">${r.cost}</td>
  4974. <td class="py-2.5 px-3 text-indigo-300 font-bold">Area ${escapeHtml(r.area || '0.0.0.0')}</td>
  4975. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(r.next_hop || r.interface || '-')}</td>
  4976. </tr>
  4977. `).join('');
  4978. }
  4979. // BGP Modals & Actions
  4980. function openBgpInstanceModal() {
  4981. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  4982. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  4983. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  4984. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  4985. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  4986. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  4987. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  4988. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  4989. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  4990. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  4991. }
  4992. function closeBgpInstanceModal() {
  4993. document.getElementById('bgp-instance-modal').classList.add('hidden');
  4994. }
  4995. async function submitBgpInstance(e) {
  4996. e.preventDefault();
  4997. const payload = {
  4998. enabled: document.getElementById('modal-bgp-enabled').checked,
  4999. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  5000. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  5001. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  5002. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  5003. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  5004. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  5005. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  5006. };
  5007. try {
  5008. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  5009. method: 'POST',
  5010. headers: { 'Content-Type': 'application/json' },
  5011. body: JSON.stringify(payload)
  5012. });
  5013. if (res.ok) {
  5014. closeBgpInstanceModal();
  5015. showToast('Success', 'BGP instance configuration updated', 'success');
  5016. loadDynamicRouting();
  5017. } else {
  5018. const err = await res.json();
  5019. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  5020. }
  5021. } catch (err) {
  5022. showToast('Error', err.message, 'error');
  5023. }
  5024. }
  5025. function openAddBgpPeerModal() {
  5026. document.getElementById('bgp-peer-form').reset();
  5027. document.getElementById('modal-bgp-peer-id').value = '';
  5028. document.getElementById('bgp-peer-modal-title').innerText = 'Add BGP Peer Connection';
  5029. document.getElementById('modal-bgp-peer-nexthop-self').checked = true;
  5030. const inFilterEl = document.getElementById('modal-bgp-peer-in-filter');
  5031. if (inFilterEl) inFilterEl.value = '';
  5032. const outFilterEl = document.getElementById('modal-bgp-peer-out-filter');
  5033. if (outFilterEl) outFilterEl.value = '';
  5034. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  5035. }
  5036. function openEditBgpPeerModal(id) {
  5037. const p = (state.bgpPeers || []).find(item => item.id === id);
  5038. if (!p) return;
  5039. document.getElementById('modal-bgp-peer-id').value = p.id;
  5040. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  5041. document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  5042. document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  5043. document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  5044. document.getElementById('modal-bgp-peer-password').value = p.password || '';
  5045. document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  5046. document.getElementById('modal-bgp-peer-nexthop-self').checked = !!p.nexthop_self;
  5047. document.getElementById('modal-bgp-peer-passive').checked = !!p.passive;
  5048. document.getElementById('modal-bgp-peer-disabled').checked = !!p.disabled;
  5049. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  5050. const inFilterEl = document.getElementById('modal-bgp-peer-in-filter');
  5051. if (inFilterEl) inFilterEl.value = p.in_filter || '';
  5052. const outFilterEl = document.getElementById('modal-bgp-peer-out-filter');
  5053. if (outFilterEl) outFilterEl.value = p.out_filter || '';
  5054. document.getElementById('bgp-peer-modal-title').innerText = 'Edit BGP Peer Connection';
  5055. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  5056. }
  5057. function closeBgpPeerModal() {
  5058. document.getElementById('bgp-peer-modal').classList.add('hidden');
  5059. }
  5060. async function submitBgpPeer(e) {
  5061. e.preventDefault();
  5062. const payload = {
  5063. id: document.getElementById('modal-bgp-peer-id').value,
  5064. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  5065. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  5066. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10),
  5067. local_address: document.getElementById('modal-bgp-peer-local-addr').value.trim(),
  5068. password: document.getElementById('modal-bgp-peer-password').value,
  5069. multihop: document.getElementById('modal-bgp-peer-multihop').checked,
  5070. nexthop_self: document.getElementById('modal-bgp-peer-nexthop-self').checked,
  5071. passive: document.getElementById('modal-bgp-peer-passive').checked,
  5072. disabled: document.getElementById('modal-bgp-peer-disabled').checked,
  5073. in_filter: (document.getElementById('modal-bgp-peer-in-filter')?.value || '').trim(),
  5074. out_filter: (document.getElementById('modal-bgp-peer-out-filter')?.value || '').trim(),
  5075. comment: document.getElementById('modal-bgp-peer-comment').value.trim()
  5076. };
  5077. try {
  5078. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  5079. method: 'POST',
  5080. headers: { 'Content-Type': 'application/json' },
  5081. body: JSON.stringify(payload)
  5082. });
  5083. if (res.ok) {
  5084. closeBgpPeerModal();
  5085. showToast('Success', 'BGP Peer saved', 'success');
  5086. loadDynamicRouting();
  5087. } else {
  5088. const err = await res.json();
  5089. showToast('Error', err.error || 'Failed to save peer', 'error');
  5090. }
  5091. } catch (err) {
  5092. showToast('Error', err.message, 'error');
  5093. }
  5094. }
  5095. async function deleteBgpPeer(id) {
  5096. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  5097. try {
  5098. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5099. if (res.ok) {
  5100. showToast('Deleted', 'BGP peer removed', 'success');
  5101. loadDynamicRouting();
  5102. }
  5103. } catch (err) {
  5104. showToast('Error', err.message, 'error');
  5105. }
  5106. }
  5107. async function toggleBgpPeerState(id, disabled) {
  5108. try {
  5109. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  5110. method: 'POST',
  5111. headers: { 'Content-Type': 'application/json' },
  5112. body: JSON.stringify({ disabled })
  5113. });
  5114. if (res.ok) {
  5115. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  5116. loadDynamicRouting();
  5117. }
  5118. } catch (err) {
  5119. showToast('Error', err.message, 'error');
  5120. }
  5121. }
  5122. function openAddBgpNetworkModal() {
  5123. document.getElementById('bgp-network-form').reset();
  5124. document.getElementById('modal-bgp-net-id').value = '';
  5125. document.getElementById('bgp-network-modal').classList.remove('hidden');
  5126. }
  5127. function closeBgpNetworkModal() {
  5128. document.getElementById('bgp-network-modal').classList.add('hidden');
  5129. }
  5130. async function submitBgpNetwork(e) {
  5131. e.preventDefault();
  5132. const payload = {
  5133. id: document.getElementById('modal-bgp-net-id').value,
  5134. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  5135. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  5136. disabled: document.getElementById('modal-bgp-net-disabled').checked
  5137. };
  5138. try {
  5139. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  5140. method: 'POST',
  5141. headers: { 'Content-Type': 'application/json' },
  5142. body: JSON.stringify(payload)
  5143. });
  5144. if (res.ok) {
  5145. closeBgpNetworkModal();
  5146. showToast('Success', 'BGP network advertisement saved', 'success');
  5147. loadDynamicRouting();
  5148. } else {
  5149. const err = await res.json();
  5150. showToast('Error', err.error || 'Failed to save network', 'error');
  5151. }
  5152. } catch (err) {
  5153. showToast('Error', err.message, 'error');
  5154. }
  5155. }
  5156. async function deleteBgpNetwork(id) {
  5157. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  5158. try {
  5159. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5160. if (res.ok) {
  5161. showToast('Deleted', 'Network advertisement removed', 'success');
  5162. loadDynamicRouting();
  5163. }
  5164. } catch (err) {
  5165. showToast('Error', err.message, 'error');
  5166. }
  5167. }
  5168. // OSPF Modals & Actions
  5169. function openOspfInstanceModal() {
  5170. const inst = state.ospfInstance || { enabled: false, router_id: '192.168.131.56', default_metric: 10 };
  5171. document.getElementById('modal-ospf-enabled').checked = !!inst.enabled;
  5172. document.getElementById('modal-ospf-router-id').value = inst.router_id || '';
  5173. document.getElementById('modal-ospf-metric').value = inst.default_metric || 10;
  5174. document.getElementById('modal-ospf-redist-conn').checked = !!inst.redistribute_connected;
  5175. document.getElementById('modal-ospf-redist-static').checked = !!inst.redistribute_static;
  5176. document.getElementById('modal-ospf-redist-bgp').checked = !!inst.redistribute_bgp;
  5177. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  5178. }
  5179. function closeOspfInstanceModal() {
  5180. document.getElementById('ospf-instance-modal').classList.add('hidden');
  5181. }
  5182. async function submitOspfInstance(e) {
  5183. e.preventDefault();
  5184. const payload = {
  5185. enabled: document.getElementById('modal-ospf-enabled').checked,
  5186. router_id: document.getElementById('modal-ospf-router-id').value.trim(),
  5187. default_metric: parseInt(document.getElementById('modal-ospf-metric').value, 10),
  5188. redistribute_connected: document.getElementById('modal-ospf-redist-conn').checked,
  5189. redistribute_static: document.getElementById('modal-ospf-redist-static').checked,
  5190. redistribute_bgp: document.getElementById('modal-ospf-redist-bgp').checked
  5191. };
  5192. try {
  5193. const res = await fetch(`${API_BASE}/routing/ospf/instance`, {
  5194. method: 'POST',
  5195. headers: { 'Content-Type': 'application/json' },
  5196. body: JSON.stringify(payload)
  5197. });
  5198. if (res.ok) {
  5199. closeOspfInstanceModal();
  5200. showToast('Success', 'OSPF instance configuration updated', 'success');
  5201. loadDynamicRouting();
  5202. } else {
  5203. const err = await res.json();
  5204. showToast('Error', err.error || 'Failed to update OSPF instance', 'error');
  5205. }
  5206. } catch (err) {
  5207. showToast('Error', err.message, 'error');
  5208. }
  5209. }
  5210. function openAddOspfAreaModal() {
  5211. document.getElementById('ospf-area-form').reset();
  5212. document.getElementById('modal-ospf-area-id').value = '';
  5213. document.getElementById('modal-ospf-area-areaid').value = '0.0.0.0';
  5214. document.getElementById('ospf-area-modal').classList.remove('hidden');
  5215. }
  5216. function closeOspfAreaModal() {
  5217. document.getElementById('ospf-area-modal').classList.add('hidden');
  5218. }
  5219. async function submitOspfArea(e) {
  5220. e.preventDefault();
  5221. const payload = {
  5222. id: document.getElementById('modal-ospf-area-id').value,
  5223. name: document.getElementById('modal-ospf-area-name').value.trim(),
  5224. area_id: document.getElementById('modal-ospf-area-areaid').value.trim(),
  5225. area_type: document.getElementById('modal-ospf-area-type').value,
  5226. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  5227. };
  5228. try {
  5229. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  5230. method: 'POST',
  5231. headers: { 'Content-Type': 'application/json' },
  5232. body: JSON.stringify(payload)
  5233. });
  5234. if (res.ok) {
  5235. closeOspfAreaModal();
  5236. showToast('Success', 'OSPF area saved', 'success');
  5237. loadDynamicRouting();
  5238. } else {
  5239. const err = await res.json();
  5240. showToast('Error', err.error || 'Failed to save area', 'error');
  5241. }
  5242. } catch (err) {
  5243. showToast('Error', err.message, 'error');
  5244. }
  5245. }
  5246. async function deleteOspfArea(id) {
  5247. if (!confirm('Are you sure you want to delete this OSPF area?')) return;
  5248. try {
  5249. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5250. if (res.ok) {
  5251. showToast('Deleted', 'OSPF area removed', 'success');
  5252. loadDynamicRouting();
  5253. }
  5254. } catch (err) {
  5255. showToast('Error', err.message, 'error');
  5256. }
  5257. }
  5258. function populateOspfInterfaceDevices() {
  5259. const select = document.getElementById('modal-ospf-iface-device');
  5260. if (!select) return;
  5261. const current = select.value;
  5262. select.innerHTML = '<option value="">Any matching interface</option>';
  5263. (state.interfaces || []).forEach(iface => {
  5264. select.innerHTML += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)} (${iface.type})</option>`;
  5265. });
  5266. if (current) select.value = current;
  5267. }
  5268. function openAddOspfInterfaceModal() {
  5269. document.getElementById('ospf-interface-form').reset();
  5270. document.getElementById('modal-ospf-iface-id').value = '';
  5271. document.getElementById('modal-ospf-iface-area').value = '0.0.0.0';
  5272. document.getElementById('modal-ospf-iface-cost').value = '10';
  5273. document.getElementById('modal-ospf-iface-priority').value = '1';
  5274. document.getElementById('modal-ospf-iface-hello').value = '10';
  5275. document.getElementById('modal-ospf-iface-dead').value = '40';
  5276. document.getElementById('ospf-interface-modal-title').innerText = 'Add OSPF Interface';
  5277. populateOspfInterfaceDevices();
  5278. document.getElementById('ospf-interface-modal').classList.remove('hidden');
  5279. }
  5280. function openEditOspfInterfaceModal(id) {
  5281. const item = (state.ospfInterfaces || []).find(i => i.id === id);
  5282. if (!item) return;
  5283. populateOspfInterfaceDevices();
  5284. document.getElementById('modal-ospf-iface-id').value = item.id;
  5285. document.getElementById('modal-ospf-iface-net').value = item.network || '';
  5286. document.getElementById('modal-ospf-iface-area').value = item.area || '0.0.0.0';
  5287. document.getElementById('modal-ospf-iface-device').value = item.interface || '';
  5288. document.getElementById('modal-ospf-iface-cost').value = item.cost || 10;
  5289. document.getElementById('modal-ospf-iface-priority').value = item.priority || 1;
  5290. document.getElementById('modal-ospf-iface-hello').value = item.hello_interval || 10;
  5291. document.getElementById('modal-ospf-iface-dead').value = item.dead_interval || 40;
  5292. document.getElementById('modal-ospf-iface-auth-type').value = item.auth_type || 'none';
  5293. document.getElementById('modal-ospf-iface-auth-key').value = item.auth_key || '';
  5294. document.getElementById('modal-ospf-iface-passive').checked = !!item.passive;
  5295. document.getElementById('modal-ospf-iface-disabled').checked = !!item.disabled;
  5296. document.getElementById('modal-ospf-iface-comment').value = item.comment || '';
  5297. document.getElementById('ospf-interface-modal-title').innerText = 'Edit OSPF Interface';
  5298. document.getElementById('ospf-interface-modal').classList.remove('hidden');
  5299. }
  5300. function closeOspfInterfaceModal() {
  5301. document.getElementById('ospf-interface-modal').classList.add('hidden');
  5302. }
  5303. async function submitOspfInterface(e) {
  5304. e.preventDefault();
  5305. const payload = {
  5306. id: document.getElementById('modal-ospf-iface-id').value,
  5307. network: document.getElementById('modal-ospf-iface-net').value.trim(),
  5308. area: document.getElementById('modal-ospf-iface-area').value.trim(),
  5309. interface: document.getElementById('modal-ospf-iface-device').value,
  5310. cost: parseInt(document.getElementById('modal-ospf-iface-cost').value, 10),
  5311. priority: parseInt(document.getElementById('modal-ospf-iface-priority').value, 10),
  5312. hello_interval: parseInt(document.getElementById('modal-ospf-iface-hello').value, 10),
  5313. dead_interval: parseInt(document.getElementById('modal-ospf-iface-dead').value, 10),
  5314. auth_type: document.getElementById('modal-ospf-iface-auth-type').value,
  5315. auth_key: document.getElementById('modal-ospf-iface-auth-key').value,
  5316. passive: document.getElementById('modal-ospf-iface-passive').checked,
  5317. disabled: document.getElementById('modal-ospf-iface-disabled').checked,
  5318. comment: document.getElementById('modal-ospf-iface-comment').value.trim()
  5319. };
  5320. try {
  5321. const res = await fetch(`${API_BASE}/routing/ospf/interfaces`, {
  5322. method: 'POST',
  5323. headers: { 'Content-Type': 'application/json' },
  5324. body: JSON.stringify(payload)
  5325. });
  5326. if (res.ok) {
  5327. closeOspfInterfaceModal();
  5328. showToast('Success', 'OSPF interface template saved', 'success');
  5329. loadDynamicRouting();
  5330. } else {
  5331. const err = await res.json();
  5332. showToast('Error', err.error || 'Failed to save interface', 'error');
  5333. }
  5334. } catch (err) {
  5335. showToast('Error', err.message, 'error');
  5336. }
  5337. }
  5338. async function deleteOspfInterface(id) {
  5339. if (!confirm('Are you sure you want to delete this OSPF interface?')) return;
  5340. try {
  5341. const res = await fetch(`${API_BASE}/routing/ospf/interfaces/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5342. if (res.ok) {
  5343. showToast('Deleted', 'OSPF interface removed', 'success');
  5344. loadDynamicRouting();
  5345. }
  5346. } catch (err) {
  5347. showToast('Error', err.message, 'error');
  5348. }
  5349. }
  5350. async function toggleOspfInterfaceState(id, disabled) {
  5351. try {
  5352. const res = await fetch(`${API_BASE}/routing/ospf/interfaces/${encodeURIComponent(id)}/state`, {
  5353. method: 'POST',
  5354. headers: { 'Content-Type': 'application/json' },
  5355. body: JSON.stringify({ disabled })
  5356. });
  5357. if (res.ok) {
  5358. showToast('Updated', `Interface ${disabled ? 'disabled' : 'enabled'}`, 'success');
  5359. loadDynamicRouting();
  5360. }
  5361. } catch (err) {
  5362. showToast('Error', err.message, 'error');
  5363. }
  5364. }
  5365. // ============================================================================
  5366. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  5367. // ============================================================================
  5368. function switchBridgeSubTab(tab) {
  5369. state.bridgeSubTab = tab;
  5370. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  5371. tabs.forEach(t => {
  5372. const panel = document.getElementById(`bridge-subtab-${t}`);
  5373. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  5374. if (panel) {
  5375. if (t === tab) panel.classList.remove('hidden');
  5376. else panel.classList.add('hidden');
  5377. }
  5378. if (btn) {
  5379. if (t === tab) {
  5380. 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';
  5381. } else {
  5382. 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';
  5383. }
  5384. }
  5385. });
  5386. const addBtn = document.getElementById('bridge-top-action-btn');
  5387. if (addBtn) {
  5388. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  5389. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  5390. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  5391. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  5392. }
  5393. if (tab === 'hosts') loadBridgeHosts();
  5394. }
  5395. function openCurrentBridgeModal() {
  5396. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  5397. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  5398. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  5399. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  5400. }
  5401. async function loadBridge() {
  5402. try {
  5403. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vlanIfacesRes] = await Promise.all([
  5404. fetch(`${API_BASE}/bridge/bridges`),
  5405. fetch(`${API_BASE}/bridge/ports`),
  5406. fetch(`${API_BASE}/bridge/vlans`),
  5407. fetch(`${API_BASE}/bridge/summary`),
  5408. fetch(`${API_BASE}/vpn/eoip`),
  5409. fetch(`${API_BASE}/vlans`)
  5410. ]);
  5411. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  5412. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  5413. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  5414. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  5415. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  5416. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  5417. // Badges & Stats
  5418. const bBridges = document.getElementById('bridge-badge-bridges');
  5419. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  5420. const bPorts = document.getElementById('bridge-badge-ports');
  5421. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  5422. const bVlans = document.getElementById('bridge-badge-vlans');
  5423. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  5424. const bHosts = document.getElementById('bridge-badge-hosts');
  5425. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  5426. const sBr = document.getElementById('bridge-stat-bridges');
  5427. if (sBr) sBr.innerText = (state.bridges || []).length;
  5428. const sPorts = document.getElementById('bridge-stat-ports');
  5429. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  5430. const sHosts = document.getElementById('bridge-stat-hosts');
  5431. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  5432. renderBridges();
  5433. renderBridgePorts();
  5434. renderBridgeVLANs();
  5435. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  5436. } catch (err) {
  5437. console.error('Failed to load bridge subsystem:', err);
  5438. }
  5439. }
  5440. // ----------------- Bridges -----------------
  5441. function renderBridges() {
  5442. const tbody = document.getElementById('bridge-table-body');
  5443. const empty = document.getElementById('bridge-empty-bridges');
  5444. const countBadge = document.getElementById('bridge-count-badge');
  5445. if (!tbody) return;
  5446. tbody.innerHTML = '';
  5447. const bridges = state.bridges || [];
  5448. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  5449. if (bridges.length === 0) {
  5450. empty?.classList.remove('hidden');
  5451. return;
  5452. }
  5453. empty?.classList.add('hidden');
  5454. bridges.forEach((b, idx) => {
  5455. const tr = document.createElement('tr');
  5456. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  5457. // Format IP addresses pill list
  5458. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  5459. if (b.ip_addresses && b.ip_addresses.length > 0) {
  5460. ipsHtml = b.ip_addresses.map(ip => `
  5461. <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">
  5462. <span>${ip}</span>
  5463. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  5464. </span>
  5465. `).join(' ');
  5466. }
  5467. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  5468. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  5469. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  5470. tr.innerHTML = `
  5471. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  5472. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  5473. <td class="py-2.5 px-3 font-bold text-white text-sm">
  5474. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  5475. </td>
  5476. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  5477. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  5478. <td class="py-2.5 px-3">
  5479. <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>
  5480. </td>
  5481. <td class="py-2.5 px-3 text-center">
  5482. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  5483. </td>
  5484. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  5485. <td class="py-2.5 px-3">
  5486. <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>
  5487. </td>
  5488. <td class="py-2.5 px-3">
  5489. <div class="flex items-center gap-1.5 flex-wrap">
  5490. ${ipsHtml}
  5491. <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>
  5492. </div>
  5493. </td>
  5494. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  5495. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  5496. </td>
  5497. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  5498. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  5499. <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>
  5500. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  5501. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5502. </td>
  5503. `;
  5504. tbody.appendChild(tr);
  5505. });
  5506. }
  5507. function openAddBridgeModal() {
  5508. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  5509. document.getElementById('bridge-modal-id').value = '';
  5510. document.getElementById('bridge-modal-name').value = 'bridge1';
  5511. document.getElementById('bridge-modal-name').disabled = false;
  5512. document.getElementById('bridge-modal-mtu').value = '1500';
  5513. document.getElementById('bridge-modal-mac').value = '';
  5514. document.getElementById('bridge-modal-stp').value = 'rstp';
  5515. document.getElementById('bridge-modal-priority').value = '32768';
  5516. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  5517. document.getElementById('bridge-modal-pvid').value = '1';
  5518. document.getElementById('bridge-modal-fastforward').checked = true;
  5519. document.getElementById('bridge-modal-comment').value = '';
  5520. document.getElementById('bridge-modal-disabled').checked = false;
  5521. toggleBridgeModalVlanFiltering();
  5522. document.getElementById('bridge-modal').classList.remove('hidden');
  5523. }
  5524. function openEditBridgeModal(id) {
  5525. const b = (state.bridges || []).find(x => x.id === id);
  5526. if (!b) return;
  5527. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  5528. document.getElementById('bridge-modal-id').value = b.id;
  5529. document.getElementById('bridge-modal-name').value = b.name;
  5530. document.getElementById('bridge-modal-name').disabled = true;
  5531. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  5532. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  5533. document.getElementById('bridge-modal-stp').value = b.stp || 'rstp';
  5534. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  5535. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  5536. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  5537. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  5538. document.getElementById('bridge-modal-comment').value = b.comment || '';
  5539. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  5540. toggleBridgeModalVlanFiltering();
  5541. document.getElementById('bridge-modal').classList.remove('hidden');
  5542. }
  5543. function closeBridgeModal() {
  5544. document.getElementById('bridge-modal').classList.add('hidden');
  5545. }
  5546. function toggleBridgeModalVlanFiltering() {
  5547. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  5548. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  5549. if (pvidBox) {
  5550. if (chk) pvidBox.classList.remove('opacity-40');
  5551. else pvidBox.classList.add('opacity-40');
  5552. }
  5553. }
  5554. async function submitSaveBridge(e) {
  5555. e.preventDefault();
  5556. const id = document.getElementById('bridge-modal-id').value;
  5557. const name = document.getElementById('bridge-modal-name').value.trim();
  5558. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  5559. const mac = document.getElementById('bridge-modal-mac').value.trim();
  5560. const stp = document.getElementById('bridge-modal-stp').value;
  5561. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  5562. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  5563. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  5564. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  5565. const comment = document.getElementById('bridge-modal-comment').value.trim();
  5566. const disabled = document.getElementById('bridge-modal-disabled').checked;
  5567. try {
  5568. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  5569. method: 'POST',
  5570. headers: { 'Content-Type': 'application/json' },
  5571. body: JSON.stringify({
  5572. id,
  5573. name,
  5574. mtu,
  5575. mac_address: mac,
  5576. stp,
  5577. priority,
  5578. vlan_filtering: vlanFiltering,
  5579. pvid,
  5580. fast_forward: fastForward,
  5581. comment,
  5582. disabled
  5583. })
  5584. });
  5585. if (res.ok) {
  5586. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  5587. closeBridgeModal();
  5588. loadBridge();
  5589. fetchData(false);
  5590. } else {
  5591. const err = await res.json();
  5592. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  5593. }
  5594. } catch (err) {
  5595. showToast('Error', err.message, 'error');
  5596. }
  5597. }
  5598. async function toggleBridgeState(id, disabled) {
  5599. try {
  5600. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  5601. method: 'POST',
  5602. headers: { 'Content-Type': 'application/json' },
  5603. body: JSON.stringify({ disabled })
  5604. });
  5605. if (res.ok) {
  5606. loadBridge();
  5607. fetchData(false);
  5608. }
  5609. } catch (err) {
  5610. showToast('Error', err.message, 'error');
  5611. }
  5612. }
  5613. async function deleteBridge(id) {
  5614. const b = (state.bridges || []).find(x => x.id === id);
  5615. const name = b ? b.name : id;
  5616. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  5617. try {
  5618. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5619. if (res.ok) {
  5620. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  5621. loadBridge();
  5622. fetchData(false);
  5623. } else {
  5624. const err = await res.json();
  5625. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  5626. }
  5627. } catch (err) {
  5628. showToast('Error', err.message, 'error');
  5629. }
  5630. }
  5631. // ----------------- Bridge IP Assignments -----------------
  5632. function openAddBridgeIPModal(id, name) {
  5633. document.getElementById('bridge-ip-modal-id').value = id;
  5634. document.getElementById('bridge-ip-modal-sub').innerText = name;
  5635. document.getElementById('bridge-ip-modal-cidr').value = '';
  5636. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  5637. }
  5638. function closeBridgeIPModal() {
  5639. document.getElementById('bridge-ip-modal').classList.add('hidden');
  5640. }
  5641. async function submitAddBridgeIP(e) {
  5642. e.preventDefault();
  5643. const id = document.getElementById('bridge-ip-modal-id').value;
  5644. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  5645. try {
  5646. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  5647. method: 'POST',
  5648. headers: { 'Content-Type': 'application/json' },
  5649. body: JSON.stringify({ ip })
  5650. });
  5651. if (res.ok) {
  5652. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  5653. closeBridgeIPModal();
  5654. loadBridge();
  5655. fetchData(false);
  5656. } else {
  5657. const err = await res.json();
  5658. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  5659. }
  5660. } catch (err) {
  5661. showToast('Error', err.message, 'error');
  5662. }
  5663. }
  5664. async function deleteBridgeIP(id, ip) {
  5665. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  5666. try {
  5667. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  5668. method: 'DELETE',
  5669. headers: { 'Content-Type': 'application/json' },
  5670. body: JSON.stringify({ ip })
  5671. });
  5672. if (res.ok) {
  5673. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  5674. loadBridge();
  5675. fetchData(false);
  5676. }
  5677. } catch (err) {
  5678. showToast('Error', err.message, 'error');
  5679. }
  5680. }
  5681. // ----------------- Bridge Ports -----------------
  5682. function renderBridgePorts() {
  5683. const tbody = document.getElementById('bridge-ports-table-body');
  5684. const empty = document.getElementById('bridge-empty-ports');
  5685. const countBadge = document.getElementById('bridge-ports-count-badge');
  5686. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  5687. if (!tbody) return;
  5688. tbody.innerHTML = '';
  5689. // Update filter select
  5690. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  5691. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  5692. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  5693. if (ports.length === 0) {
  5694. empty?.classList.remove('hidden');
  5695. return;
  5696. }
  5697. empty?.classList.add('hidden');
  5698. ports.forEach((p, idx) => {
  5699. const tr = document.createElement('tr');
  5700. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  5701. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  5702. tr.innerHTML = `
  5703. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  5704. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  5705. <td class="py-2.5 px-3 font-bold text-white text-sm">
  5706. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  5707. </td>
  5708. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  5709. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  5710. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  5711. <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>
  5712. <td class="py-2.5 px-3">
  5713. ${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>'}
  5714. </td>
  5715. <td class="py-2.5 px-3">
  5716. <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>
  5717. </td>
  5718. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  5719. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  5720. <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>
  5721. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  5722. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5723. </td>
  5724. `;
  5725. tbody.appendChild(tr);
  5726. });
  5727. }
  5728. function openAddBridgePortModal() {
  5729. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  5730. document.getElementById('bridge-port-modal-id').value = '';
  5731. populateBridgeSelect('bridge-port-modal-bridge');
  5732. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  5733. document.getElementById('bridge-port-modal-pvid').value = '1';
  5734. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  5735. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  5736. document.getElementById('bridge-port-modal-horizon').value = '0';
  5737. document.getElementById('bridge-port-modal-pathcost').value = '10';
  5738. document.getElementById('bridge-port-modal-priority').value = '128';
  5739. document.getElementById('bridge-port-modal-learn').checked = true;
  5740. document.getElementById('bridge-port-modal-comment').value = '';
  5741. document.getElementById('bridge-port-modal-disabled').checked = false;
  5742. document.getElementById('bridge-port-modal').classList.remove('hidden');
  5743. }
  5744. function openEditBridgePortModal(id) {
  5745. const p = (state.bridgePorts || []).find(x => x.id === id);
  5746. if (!p) return;
  5747. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  5748. document.getElementById('bridge-port-modal-id').value = p.id;
  5749. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  5750. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  5751. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  5752. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  5753. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  5754. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  5755. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  5756. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  5757. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  5758. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  5759. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  5760. document.getElementById('bridge-port-modal').classList.remove('hidden');
  5761. }
  5762. function closeBridgePortModal() {
  5763. document.getElementById('bridge-port-modal').classList.add('hidden');
  5764. }
  5765. async function submitSaveBridgePort(e) {
  5766. e.preventDefault();
  5767. const id = document.getElementById('bridge-port-modal-id').value;
  5768. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  5769. const iface = document.getElementById('bridge-port-modal-interface').value;
  5770. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  5771. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  5772. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  5773. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  5774. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  5775. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  5776. const learn = document.getElementById('bridge-port-modal-learn').checked;
  5777. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  5778. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  5779. try {
  5780. const res = await fetch(`${API_BASE}/bridge/ports`, {
  5781. method: 'POST',
  5782. headers: { 'Content-Type': 'application/json' },
  5783. body: JSON.stringify({
  5784. id,
  5785. bridge,
  5786. interface: iface,
  5787. pvid,
  5788. frame_types: frameTypes,
  5789. ingress_filtering: ingressFiltering,
  5790. horizon,
  5791. path_cost: pathCost,
  5792. priority,
  5793. learn,
  5794. comment,
  5795. disabled
  5796. })
  5797. });
  5798. if (res.ok) {
  5799. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  5800. closeBridgePortModal();
  5801. loadBridge();
  5802. fetchData(false);
  5803. } else {
  5804. const err = await res.json();
  5805. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  5806. }
  5807. } catch (err) {
  5808. showToast('Error', err.message, 'error');
  5809. }
  5810. }
  5811. async function toggleBridgePortState(id, disabled) {
  5812. try {
  5813. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  5814. method: 'POST',
  5815. headers: { 'Content-Type': 'application/json' },
  5816. body: JSON.stringify({ disabled })
  5817. });
  5818. if (res.ok) {
  5819. loadBridge();
  5820. fetchData(false);
  5821. }
  5822. } catch (err) {
  5823. showToast('Error', err.message, 'error');
  5824. }
  5825. }
  5826. async function deleteBridgePort(id) {
  5827. const p = (state.bridgePorts || []).find(x => x.id === id);
  5828. const iface = p ? p.interface : id;
  5829. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  5830. try {
  5831. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5832. if (res.ok) {
  5833. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  5834. loadBridge();
  5835. fetchData(false);
  5836. }
  5837. } catch (err) {
  5838. showToast('Error', err.message, 'error');
  5839. }
  5840. }
  5841. // ----------------- Bridge VLANs -----------------
  5842. function renderBridgeVLANs() {
  5843. const tbody = document.getElementById('bridge-vlans-table-body');
  5844. const empty = document.getElementById('bridge-empty-vlans');
  5845. const countBadge = document.getElementById('bridge-vlans-count-badge');
  5846. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  5847. if (!tbody) return;
  5848. tbody.innerHTML = '';
  5849. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  5850. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  5851. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  5852. if (vlans.length === 0) {
  5853. empty?.classList.remove('hidden');
  5854. return;
  5855. }
  5856. empty?.classList.add('hidden');
  5857. vlans.forEach((v, idx) => {
  5858. const tr = document.createElement('tr');
  5859. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  5860. const taggedHtml = (v.tagged && v.tagged.length > 0)
  5861. ? 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(' ')
  5862. : '<span class="text-slate-600">none</span>';
  5863. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  5864. ? 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(' ')
  5865. : '<span class="text-slate-600">none</span>';
  5866. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  5867. tr.innerHTML = `
  5868. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  5869. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  5870. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  5871. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  5872. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  5873. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  5874. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  5875. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  5876. <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>
  5877. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  5878. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5879. </td>
  5880. `;
  5881. tbody.appendChild(tr);
  5882. });
  5883. }
  5884. function openAddBridgeVLANModal() {
  5885. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  5886. document.getElementById('bridge-vlan-modal-id').value = '';
  5887. populateBridgeSelect('bridge-vlan-modal-bridge');
  5888. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  5889. document.getElementById('bridge-vlan-modal-comment').value = '';
  5890. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  5891. updateBridgeVlanPortCheckboxes();
  5892. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  5893. }
  5894. function openEditBridgeVLANModal(id) {
  5895. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  5896. if (!v) return;
  5897. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  5898. document.getElementById('bridge-vlan-modal-id').value = v.id;
  5899. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  5900. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  5901. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  5902. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  5903. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  5904. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  5905. }
  5906. function closeBridgeVlanModal() {
  5907. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  5908. }
  5909. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  5910. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  5911. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  5912. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  5913. if (!taggedBox || !untaggedBox) return;
  5914. // Ports belonging to the selected bridge
  5915. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  5916. if (memberPorts.length === 0) {
  5917. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  5918. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  5919. return;
  5920. }
  5921. taggedBox.innerHTML = memberPorts.map(p => `
  5922. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  5923. <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">
  5924. <span>${p.interface}</span>
  5925. </label>
  5926. `).join('');
  5927. untaggedBox.innerHTML = memberPorts.map(p => `
  5928. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  5929. <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">
  5930. <span>${p.interface}</span>
  5931. </label>
  5932. `).join('');
  5933. }
  5934. async function submitSaveBridgeVLAN(e) {
  5935. e.preventDefault();
  5936. const id = document.getElementById('bridge-vlan-modal-id').value;
  5937. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  5938. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  5939. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  5940. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  5941. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  5942. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  5943. try {
  5944. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  5945. method: 'POST',
  5946. headers: { 'Content-Type': 'application/json' },
  5947. body: JSON.stringify({
  5948. id,
  5949. bridge,
  5950. vlan_ids: vlanIDs,
  5951. tagged,
  5952. untagged,
  5953. comment,
  5954. disabled
  5955. })
  5956. });
  5957. if (res.ok) {
  5958. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  5959. closeBridgeVlanModal();
  5960. loadBridge();
  5961. } else {
  5962. const err = await res.json();
  5963. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  5964. }
  5965. } catch (err) {
  5966. showToast('Error', err.message, 'error');
  5967. }
  5968. }
  5969. async function toggleBridgeVLANState(id, disabled) {
  5970. try {
  5971. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  5972. method: 'POST',
  5973. headers: { 'Content-Type': 'application/json' },
  5974. body: JSON.stringify({ disabled })
  5975. });
  5976. if (res.ok) loadBridge();
  5977. } catch (err) {
  5978. showToast('Error', err.message, 'error');
  5979. }
  5980. }
  5981. async function deleteBridgeVLAN(id) {
  5982. if (!confirm('Delete this bridge VLAN entry?')) return;
  5983. try {
  5984. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5985. if (res.ok) {
  5986. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  5987. loadBridge();
  5988. }
  5989. } catch (err) {
  5990. showToast('Error', err.message, 'error');
  5991. }
  5992. }
  5993. // ----------------- Hosts / MAC Table -----------------
  5994. async function loadBridgeHosts() {
  5995. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  5996. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  5997. try {
  5998. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  5999. const res = await fetch(url);
  6000. if (res.ok) {
  6001. state.bridgeHosts = await res.json();
  6002. renderBridgeHosts();
  6003. }
  6004. } catch (err) {
  6005. console.error('Failed to load bridge hosts:', err);
  6006. }
  6007. }
  6008. function renderBridgeHosts() {
  6009. const tbody = document.getElementById('bridge-hosts-table-body');
  6010. const empty = document.getElementById('bridge-empty-hosts');
  6011. const countBadge = document.getElementById('bridge-hosts-count-badge');
  6012. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  6013. if (!tbody) return;
  6014. tbody.innerHTML = '';
  6015. const hosts = (state.bridgeHosts || []).filter(h => {
  6016. if (!search) return true;
  6017. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  6018. });
  6019. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  6020. if (hosts.length === 0) {
  6021. empty?.classList.remove('hidden');
  6022. return;
  6023. }
  6024. empty?.classList.add('hidden');
  6025. hosts.forEach(h => {
  6026. const tr = document.createElement('tr');
  6027. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  6028. let flagBadges = '';
  6029. 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>';
  6030. 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>';
  6031. 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>';
  6032. tr.innerHTML = `
  6033. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  6034. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  6035. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  6036. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  6037. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  6038. <td class="py-2.5 px-3">${flagBadges}</td>
  6039. `;
  6040. tbody.appendChild(tr);
  6041. });
  6042. }
  6043. async function flushBridgeHosts() {
  6044. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  6045. if (!selBridge) {
  6046. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  6047. return;
  6048. }
  6049. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  6050. try {
  6051. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  6052. method: 'POST',
  6053. headers: { 'Content-Type': 'application/json' },
  6054. body: JSON.stringify({ bridge: selBridge })
  6055. });
  6056. if (res.ok) {
  6057. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  6058. loadBridgeHosts();
  6059. }
  6060. } catch (err) {
  6061. showToast('Error', err.message, 'error');
  6062. }
  6063. }
  6064. // ----------------- Helpers -----------------
  6065. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  6066. const sel = document.getElementById(selectId);
  6067. if (!sel) return;
  6068. const prevVal = currentVal || sel.value;
  6069. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  6070. (state.bridges || []).forEach(b => {
  6071. const opt = document.createElement('option');
  6072. opt.value = b.name;
  6073. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  6074. if (b.name === prevVal) opt.selected = true;
  6075. sel.appendChild(opt);
  6076. });
  6077. }
  6078. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  6079. const sel = document.getElementById(selectId);
  6080. if (!sel) return;
  6081. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  6082. // 1. Physical Interfaces
  6083. const grpPhys = document.createElement('optgroup');
  6084. grpPhys.label = 'Physical Interfaces';
  6085. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  6086. const opt = document.createElement('option');
  6087. opt.value = i.name;
  6088. opt.innerText = `${i.name} (${i.role || i.type})`;
  6089. if (i.name === currentVal) opt.selected = true;
  6090. grpPhys.appendChild(opt);
  6091. });
  6092. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  6093. // 2. VLAN Sub-interfaces
  6094. const grpVlans = document.createElement('optgroup');
  6095. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  6096. (state.vlans || []).forEach(v => {
  6097. const opt = document.createElement('option');
  6098. opt.value = v.name;
  6099. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  6100. if (v.name === currentVal) opt.selected = true;
  6101. grpVlans.appendChild(opt);
  6102. });
  6103. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  6104. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  6105. const grpEoip = document.createElement('optgroup');
  6106. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  6107. (state.eoipTunnels || []).forEach(t => {
  6108. const opt = document.createElement('option');
  6109. opt.value = t.name;
  6110. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  6111. if (t.name === currentVal) opt.selected = true;
  6112. grpEoip.appendChild(opt);
  6113. });
  6114. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  6115. }
  6116. // -------------------------------------------------------------
  6117. // Routing Filters Management (/routing filter)
  6118. // -------------------------------------------------------------
  6119. function renderRoutingFilters() {
  6120. const tbody = document.getElementById('routing-filters-table-body');
  6121. if (!tbody) return;
  6122. const empty = document.getElementById('routing-filters-empty');
  6123. const countBadge = document.getElementById('routing-filters-count-badge');
  6124. const navBadge = document.getElementById('badge-filters-count');
  6125. const chainSelect = document.getElementById('routing-filter-chain-select');
  6126. const allRules = state.routingFilters || [];
  6127. if (navBadge) navBadge.innerText = allRules.length;
  6128. // Populate chain filter select options dynamically
  6129. if (chainSelect) {
  6130. const currentVal = state.filterChainSelected || 'all';
  6131. const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
  6132. chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
  6133. uniqueChains.map(ch => {
  6134. const count = allRules.filter(r => r.chain === ch).length;
  6135. return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
  6136. }).join('');
  6137. chainSelect.value = currentVal;
  6138. }
  6139. // Filter rules by selected chain
  6140. const filteredRules = (state.filterChainSelected && state.filterChainSelected !== 'all')
  6141. ? allRules.filter(r => r.chain === state.filterChainSelected)
  6142. : allRules.slice();
  6143. // Sort by chain then rule_order
  6144. filteredRules.sort((a, b) => {
  6145. if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
  6146. return (a.rule_order || 0) - (b.rule_order || 0);
  6147. });
  6148. if (countBadge) countBadge.innerText = `${filteredRules.length} Rules`;
  6149. if (filteredRules.length === 0) {
  6150. tbody.innerHTML = '';
  6151. if (empty) empty.classList.remove('hidden');
  6152. return;
  6153. }
  6154. if (empty) empty.classList.add('hidden');
  6155. tbody.innerHTML = filteredRules.map(r => {
  6156. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  6157. const flagX = r.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  6158. let actionBadge = '';
  6159. if (r.action === 'accept') {
  6160. 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>';
  6161. } else if (r.action === 'discard') {
  6162. 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>';
  6163. } else if (r.action === 'reject') {
  6164. 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>';
  6165. } else {
  6166. 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>`;
  6167. }
  6168. // Prefix match
  6169. let matchPfx = '';
  6170. if (r.prefix) {
  6171. matchPfx = `<span class="font-bold text-white">${escapeHtml(r.prefix)}</span>`;
  6172. if (r.prefix_len) {
  6173. matchPfx += ` <span class="text-slate-400 text-[11px] font-normal">[${escapeHtml(r.prefix_len)}]</span>`;
  6174. }
  6175. } else {
  6176. matchPfx = '<span class="text-slate-500 italic">any prefix</span>';
  6177. }
  6178. // Other matches
  6179. const matchExtra = [];
  6180. if (r.match_protocol && r.match_protocol !== 'any') {
  6181. 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>`);
  6182. }
  6183. if (r.match_as_path) {
  6184. 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>`);
  6185. }
  6186. if (r.match_community) {
  6187. 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>`);
  6188. }
  6189. const matchExtraHtml = matchExtra.length > 0 ? matchExtra.join(' ') : '<span class="text-slate-600">-</span>';
  6190. // Set modifications
  6191. const setBadges = [];
  6192. if (r.set_local_pref > 0) {
  6193. 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>`);
  6194. }
  6195. if (r.set_metric > 0) {
  6196. 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>`);
  6197. }
  6198. if (r.set_as_prepend > 0) {
  6199. 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>`);
  6200. }
  6201. if (r.set_community) {
  6202. 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>`);
  6203. }
  6204. if (r.set_next_hop) {
  6205. 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>`);
  6206. }
  6207. const setHtml = setBadges.length > 0 ? setBadges.join(' ') : '<span class="text-slate-600">-</span>';
  6208. return `
  6209. <tr class="hover:bg-slate-800/40 transition">
  6210. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagX}</td>
  6211. <td class="py-2.5 px-3 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  6212. <td class="py-2.5 px-3">
  6213. <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>
  6214. </td>
  6215. <td class="py-2.5 px-3">${actionBadge}</td>
  6216. <td class="py-2.5 px-3 font-mono">${matchPfx}</td>
  6217. <td class="py-2.5 px-3 space-x-1">${matchExtraHtml}</td>
  6218. <td class="py-2.5 px-3 space-x-1 font-mono">${setHtml}</td>
  6219. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  6220. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  6221. <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'}">
  6222. ${r.disabled ? 'Enable' : 'Disable'}
  6223. </button>
  6224. <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">
  6225. Edit
  6226. </button>
  6227. <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">
  6228. Delete
  6229. </button>
  6230. </td>
  6231. </tr>
  6232. `;
  6233. }).join('');
  6234. }
  6235. function filterRoutingFiltersByChain(chain) {
  6236. state.filterChainSelected = chain;
  6237. renderRoutingFilters();
  6238. }
  6239. function openAddRoutingFilterModal(defaultChain = '') {
  6240. const form = document.getElementById('routing-filter-form');
  6241. if (form) form.reset();
  6242. const idEl = document.getElementById('modal-rf-id');
  6243. if (idEl) idEl.value = '';
  6244. const titleEl = document.getElementById('modal-rf-title');
  6245. if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
  6246. const chainEl = document.getElementById('modal-rf-chain');
  6247. if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
  6248. const orderEl = document.getElementById('modal-rf-order');
  6249. if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
  6250. const actEl = document.getElementById('modal-rf-action');
  6251. if (actEl) actEl.value = 'accept';
  6252. const protoEl = document.getElementById('modal-rf-protocol');
  6253. if (protoEl) protoEl.value = 'any';
  6254. const disEl = document.getElementById('modal-rf-disabled');
  6255. if (disEl) disEl.checked = false;
  6256. const modal = document.getElementById('modal-routing-filter');
  6257. if (modal) modal.classList.remove('hidden');
  6258. }
  6259. function openEditRoutingFilterModal(id) {
  6260. const r = (state.routingFilters || []).find(item => item.id === id);
  6261. if (!r) return;
  6262. const idEl = document.getElementById('modal-rf-id');
  6263. if (idEl) idEl.value = r.id;
  6264. const titleEl = document.getElementById('modal-rf-title');
  6265. if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
  6266. const chainEl = document.getElementById('modal-rf-chain');
  6267. if (chainEl) chainEl.value = r.chain || '';
  6268. const orderEl = document.getElementById('modal-rf-order');
  6269. if (orderEl) orderEl.value = r.rule_order || 10;
  6270. const actEl = document.getElementById('modal-rf-action');
  6271. if (actEl) actEl.value = r.action || 'accept';
  6272. const pfxEl = document.getElementById('modal-rf-prefix');
  6273. if (pfxEl) pfxEl.value = r.prefix || '';
  6274. const pfxLenEl = document.getElementById('modal-rf-prefix-len');
  6275. if (pfxLenEl) pfxLenEl.value = r.prefix_len || '';
  6276. const protoEl = document.getElementById('modal-rf-protocol');
  6277. if (protoEl) protoEl.value = r.match_protocol || 'any';
  6278. const aspEl = document.getElementById('modal-rf-as-path');
  6279. if (aspEl) aspEl.value = r.match_as_path || '';
  6280. const commEl = document.getElementById('modal-rf-community');
  6281. if (commEl) commEl.value = r.match_community || '';
  6282. const lpEl = document.getElementById('modal-rf-set-local-pref');
  6283. if (lpEl) lpEl.value = r.set_local_pref || '';
  6284. const metEl = document.getElementById('modal-rf-set-metric');
  6285. if (metEl) metEl.value = r.set_metric || '';
  6286. const prepEl = document.getElementById('modal-rf-set-as-prepend');
  6287. if (prepEl) prepEl.value = r.set_as_prepend || '';
  6288. const setCommEl = document.getElementById('modal-rf-set-community');
  6289. if (setCommEl) setCommEl.value = r.set_community || '';
  6290. const nhEl = document.getElementById('modal-rf-set-next-hop');
  6291. if (nhEl) nhEl.value = r.set_next_hop || '';
  6292. const comEl = document.getElementById('modal-rf-comment');
  6293. if (comEl) comEl.value = r.comment || '';
  6294. const disEl = document.getElementById('modal-rf-disabled');
  6295. if (disEl) disEl.checked = !!r.disabled;
  6296. const modal = document.getElementById('modal-routing-filter');
  6297. if (modal) modal.classList.remove('hidden');
  6298. }
  6299. function closeRoutingFilterModal() {
  6300. const modal = document.getElementById('modal-routing-filter');
  6301. if (modal) modal.classList.add('hidden');
  6302. }
  6303. async function submitRoutingFilter(e) {
  6304. e.preventDefault();
  6305. const payload = {
  6306. id: document.getElementById('modal-rf-id').value,
  6307. chain: document.getElementById('modal-rf-chain').value.trim(),
  6308. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  6309. action: document.getElementById('modal-rf-action').value,
  6310. prefix: document.getElementById('modal-rf-prefix').value.trim(),
  6311. prefix_len: document.getElementById('modal-rf-prefix-len').value.trim(),
  6312. match_protocol: document.getElementById('modal-rf-protocol').value,
  6313. match_as_path: document.getElementById('modal-rf-as-path').value.trim(),
  6314. match_community: document.getElementById('modal-rf-community').value.trim(),
  6315. set_local_pref: parseInt(document.getElementById('modal-rf-set-local-pref').value, 10) || 0,
  6316. set_metric: parseInt(document.getElementById('modal-rf-set-metric').value, 10) || 0,
  6317. set_as_prepend: parseInt(document.getElementById('modal-rf-set-as-prepend').value, 10) || 0,
  6318. set_community: document.getElementById('modal-rf-set-community').value.trim(),
  6319. set_next_hop: document.getElementById('modal-rf-set-next-hop').value.trim(),
  6320. comment: document.getElementById('modal-rf-comment').value.trim(),
  6321. disabled: document.getElementById('modal-rf-disabled').checked
  6322. };
  6323. try {
  6324. const res = await fetch(`${API_BASE}/routing/filters`, {
  6325. method: 'POST',
  6326. headers: { 'Content-Type': 'application/json' },
  6327. body: JSON.stringify(payload)
  6328. });
  6329. if (res.ok) {
  6330. closeRoutingFilterModal();
  6331. showToast('Success', 'Routing filter rule saved', 'success');
  6332. loadDynamicRouting();
  6333. } else {
  6334. const err = await res.json();
  6335. showToast('Error', err.error || 'Failed to save filter rule', 'error');
  6336. }
  6337. } catch (err) {
  6338. showToast('Error', err.message, 'error');
  6339. }
  6340. }
  6341. async function deleteRoutingFilter(id) {
  6342. if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
  6343. try {
  6344. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6345. if (res.ok) {
  6346. showToast('Deleted', 'Routing filter rule removed', 'info');
  6347. loadDynamicRouting();
  6348. } else {
  6349. const err = await res.json();
  6350. showToast('Error', err.error || 'Failed to delete rule', 'error');
  6351. }
  6352. } catch (err) {
  6353. showToast('Error', err.message, 'error');
  6354. }
  6355. }
  6356. async function toggleRoutingFilterState(id, disabled) {
  6357. try {
  6358. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
  6359. method: 'POST',
  6360. headers: { 'Content-Type': 'application/json' },
  6361. body: JSON.stringify({ disabled })
  6362. });
  6363. if (res.ok) {
  6364. showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  6365. loadDynamicRouting();
  6366. } else {
  6367. const err = await res.json();
  6368. showToast('Error', err.error || 'Failed to toggle rule state', 'error');
  6369. }
  6370. } catch (err) {
  6371. showToast('Error', err.message, 'error');
  6372. }
  6373. }
  6374. // ==========================================
  6375. // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
  6376. // ==========================================
  6377. function loadToolsView() {
  6378. populateToolsInterfaces();
  6379. switchToolsSubTab(state.activeToolsSubTab || 'ping');
  6380. }
  6381. function populateToolsInterfaces() {
  6382. const pingSel = document.getElementById('tools-ping-iface');
  6383. const traceSel = document.getElementById('tools-tr-iface');
  6384. let opts = '<option value="">Auto (Default Route)</option>';
  6385. if (Array.isArray(state.interfaces)) {
  6386. state.interfaces.forEach(iface => {
  6387. if (iface.name) {
  6388. opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
  6389. }
  6390. });
  6391. }
  6392. if (pingSel) {
  6393. const cur = pingSel.value;
  6394. pingSel.innerHTML = opts;
  6395. if (cur) pingSel.value = cur;
  6396. }
  6397. if (traceSel) {
  6398. const cur = traceSel.value;
  6399. traceSel.innerHTML = opts;
  6400. if (cur) traceSel.value = cur;
  6401. }
  6402. }
  6403. function switchToolsSubTab(subTab) {
  6404. state.activeToolsSubTab = subTab;
  6405. const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
  6406. tabs.forEach(t => {
  6407. const btn = document.getElementById(`tools-subtab-btn-${t}`);
  6408. const view = document.getElementById(`tools-view-${t}`);
  6409. if (btn) {
  6410. if (t === subTab) {
  6411. 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';
  6412. } else {
  6413. 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';
  6414. }
  6415. }
  6416. if (view) {
  6417. if (t === subTab) {
  6418. view.classList.remove('hidden');
  6419. } else {
  6420. view.classList.add('hidden');
  6421. }
  6422. }
  6423. });
  6424. }
  6425. function setPortPreset(port) {
  6426. const input = document.getElementById('tools-port-num');
  6427. if (input) input.value = port;
  6428. }
  6429. let pingAbortController = null;
  6430. let tracerouteAbortController = null;
  6431. function clearPingTable() {
  6432. const tbody = document.getElementById('tools-ping-tbody');
  6433. if (tbody) tbody.innerHTML = '';
  6434. const rawEl = document.getElementById('tools-ping-raw');
  6435. if (rawEl) rawEl.innerText = '';
  6436. const sentEl = document.getElementById('tools-ping-stat-sent');
  6437. if (sentEl) sentEl.innerText = '0';
  6438. const recvEl = document.getElementById('tools-ping-stat-recv');
  6439. if (recvEl) recvEl.innerText = '0';
  6440. const lossEl = document.getElementById('tools-ping-stat-loss');
  6441. if (lossEl) lossEl.innerText = '0%';
  6442. const avgEl = document.getElementById('tools-ping-stat-avg');
  6443. if (avgEl) avgEl.innerText = '0 ms';
  6444. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  6445. if (minMaxEl) minMaxEl.innerText = '-';
  6446. const badge = document.getElementById('tools-ping-status-badge');
  6447. if (badge) {
  6448. badge.className = '';
  6449. badge.innerText = '';
  6450. }
  6451. }
  6452. function clearTracerouteTable() {
  6453. const tbody = document.getElementById('tools-tr-tbody');
  6454. if (tbody) tbody.innerHTML = '';
  6455. const rawEl = document.getElementById('tools-tr-raw');
  6456. if (rawEl) rawEl.innerText = '';
  6457. const statHops = document.getElementById('tools-tr-hops-count');
  6458. if (statHops) statHops.innerText = '0 Hops';
  6459. }
  6460. function resetPingButton() {
  6461. const btn = document.getElementById('tools-ping-btn');
  6462. const btnText = document.getElementById('tools-ping-btn-text');
  6463. const spinner = document.getElementById('tools-ping-spinner');
  6464. if (btn) {
  6465. btn.disabled = false;
  6466. 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';
  6467. }
  6468. if (btnText) btnText.innerText = 'Start Ping';
  6469. if (spinner) spinner.classList.add('hidden');
  6470. }
  6471. function setPingRunningButton() {
  6472. const btn = document.getElementById('tools-ping-btn');
  6473. const btnText = document.getElementById('tools-ping-btn-text');
  6474. const spinner = document.getElementById('tools-ping-spinner');
  6475. if (btn) {
  6476. btn.disabled = false;
  6477. 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';
  6478. }
  6479. if (btnText) btnText.innerText = 'Stop Ping';
  6480. if (spinner) spinner.classList.remove('hidden');
  6481. }
  6482. function resetTracerouteButton() {
  6483. const btn = document.getElementById('tools-tr-btn');
  6484. const btnText = document.getElementById('tools-tr-btn-text');
  6485. const spinner = document.getElementById('tools-tr-spinner');
  6486. if (btn) {
  6487. btn.disabled = false;
  6488. 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';
  6489. }
  6490. if (btnText) btnText.innerText = 'Start Traceroute';
  6491. if (spinner) spinner.classList.add('hidden');
  6492. }
  6493. function setTracerouteRunningButton() {
  6494. const btn = document.getElementById('tools-tr-btn');
  6495. const btnText = document.getElementById('tools-tr-btn-text');
  6496. const spinner = document.getElementById('tools-tr-spinner');
  6497. if (btn) {
  6498. btn.disabled = false;
  6499. 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';
  6500. }
  6501. if (btnText) btnText.innerText = 'Stop Traceroute';
  6502. if (spinner) spinner.classList.remove('hidden');
  6503. }
  6504. async function executePing(e) {
  6505. if (e) e.preventDefault();
  6506. // If already running, clicking the button stops the stream!
  6507. if (pingAbortController) {
  6508. pingAbortController.abort();
  6509. pingAbortController = null;
  6510. resetPingButton();
  6511. showToast('Ping Stopped', 'Live ping stopped by user', 'info');
  6512. return;
  6513. }
  6514. const target = document.getElementById('tools-ping-target')?.value?.trim();
  6515. const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
  6516. const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
  6517. const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '3', 10);
  6518. const iface = document.getElementById('tools-ping-iface')?.value || '';
  6519. const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
  6520. if (!target) {
  6521. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  6522. return;
  6523. }
  6524. clearPingTable();
  6525. const resCard = document.getElementById('tools-ping-results');
  6526. if (resCard) resCard.classList.remove('hidden');
  6527. pingAbortController = new AbortController();
  6528. setPingRunningButton();
  6529. try {
  6530. const res = await fetch(`${API_BASE}/tools/ping/stream`, {
  6531. method: 'POST',
  6532. headers: { 'Content-Type': 'application/json' },
  6533. body: JSON.stringify({
  6534. target,
  6535. count,
  6536. size,
  6537. timeout,
  6538. interface: iface,
  6539. dont_frag: dontFrag
  6540. }),
  6541. signal: pingAbortController.signal
  6542. });
  6543. if (!res.ok) {
  6544. const errText = await res.text();
  6545. showToast('Ping Error', errText || 'Failed to start live ping', 'error');
  6546. resetPingButton();
  6547. pingAbortController = null;
  6548. return;
  6549. }
  6550. const reader = res.body.getReader();
  6551. const decoder = new TextDecoder('utf-8');
  6552. let buffer = '';
  6553. while (true) {
  6554. const { done, value } = await reader.read();
  6555. if (done) break;
  6556. buffer += decoder.decode(value, { stream: true });
  6557. const blocks = buffer.split('\n\n');
  6558. buffer = blocks.pop() || '';
  6559. for (const block of blocks) {
  6560. const trimmed = block.trim();
  6561. if (!trimmed) continue;
  6562. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  6563. try {
  6564. const evt = JSON.parse(line);
  6565. handleLivePingEvent(evt);
  6566. } catch (parseErr) {
  6567. console.warn('Ping SSE parse error:', parseErr, line);
  6568. }
  6569. }
  6570. }
  6571. } catch (err) {
  6572. if (err.name === 'AbortError') {
  6573. // User aborted normally
  6574. } else {
  6575. showToast('Ping Error', err.message, 'error');
  6576. }
  6577. } finally {
  6578. pingAbortController = null;
  6579. resetPingButton();
  6580. }
  6581. }
  6582. function handleLivePingEvent(evt) {
  6583. const sentEl = document.getElementById('tools-ping-stat-sent');
  6584. const recvEl = document.getElementById('tools-ping-stat-recv');
  6585. const lossEl = document.getElementById('tools-ping-stat-loss');
  6586. const avgEl = document.getElementById('tools-ping-stat-avg');
  6587. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  6588. const badge = document.getElementById('tools-ping-status-badge');
  6589. const tbody = document.getElementById('tools-ping-tbody');
  6590. const rawEl = document.getElementById('tools-ping-raw');
  6591. if (evt.raw && rawEl) {
  6592. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  6593. rawEl.scrollTop = rawEl.scrollHeight;
  6594. }
  6595. if (evt.type === 'reply') {
  6596. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  6597. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  6598. if (lossEl && evt.packet_loss_pct !== undefined) {
  6599. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  6600. lossEl.className = evt.packet_loss_pct === 0
  6601. ? 'text-base font-bold font-mono text-emerald-400 mt-1'
  6602. : (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');
  6603. }
  6604. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  6605. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  6606. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  6607. }
  6608. if (badge) {
  6609. if (evt.packet_loss_pct === 0) {
  6610. 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';
  6611. badge.innerText = '100% OK';
  6612. } else {
  6613. 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';
  6614. badge.innerText = `${evt.packet_loss_pct.toFixed(0)}% LOSS`;
  6615. }
  6616. }
  6617. if (tbody) {
  6618. const tr = document.createElement('tr');
  6619. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  6620. tr.innerHTML = `
  6621. <td class="py-2 px-3 text-slate-300">#${evt.seq}</td>
  6622. <td class="py-2 px-3 font-semibold text-white">${escapeHtml(evt.from)}</td>
  6623. <td class="py-2 px-3 text-slate-400">${evt.bytes} bytes</td>
  6624. <td class="py-2 px-3 text-slate-300">${evt.ttl}</td>
  6625. <td class="py-2 px-3 font-bold text-amber-300">${evt.time_ms.toFixed(2)} ms</td>
  6626. <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>
  6627. `;
  6628. tbody.appendChild(tr);
  6629. }
  6630. } else if (evt.type === 'timeout') {
  6631. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  6632. if (lossEl && evt.packet_loss_pct !== undefined) {
  6633. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  6634. 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';
  6635. }
  6636. if (badge) {
  6637. 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';
  6638. badge.innerText = `${evt.packet_loss_pct?.toFixed(0) || 100}% LOSS`;
  6639. }
  6640. if (tbody) {
  6641. const tr = document.createElement('tr');
  6642. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs opacity-75';
  6643. tr.innerHTML = `
  6644. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  6645. <td class="py-2 px-3 font-semibold text-slate-500 italic">Request timed out</td>
  6646. <td class="py-2 px-3 text-slate-600">--</td>
  6647. <td class="py-2 px-3 text-slate-600">--</td>
  6648. <td class="py-2 px-3 font-bold text-slate-500">* * *</td>
  6649. <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>
  6650. `;
  6651. tbody.appendChild(tr);
  6652. }
  6653. } else if (evt.type === 'unreach') {
  6654. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  6655. if (lossEl && evt.packet_loss_pct !== undefined) {
  6656. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  6657. lossEl.className = 'text-base font-bold font-mono text-rose-400 mt-1';
  6658. }
  6659. if (badge) {
  6660. 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';
  6661. badge.innerText = 'UNREACHABLE';
  6662. }
  6663. if (tbody) {
  6664. const tr = document.createElement('tr');
  6665. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  6666. tr.innerHTML = `
  6667. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  6668. <td class="py-2 px-3 font-semibold text-rose-400">${escapeHtml(evt.from || 'Gateway')}</td>
  6669. <td class="py-2 px-3 text-slate-600">--</td>
  6670. <td class="py-2 px-3 text-slate-600">--</td>
  6671. <td class="py-2 px-3 font-bold text-rose-400 text-xs">${escapeHtml(evt.message || 'Unreachable')}</td>
  6672. <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>
  6673. `;
  6674. tbody.appendChild(tr);
  6675. }
  6676. } else if (evt.type === 'stats') {
  6677. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  6678. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  6679. if (lossEl && evt.packet_loss_pct !== undefined) lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  6680. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  6681. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  6682. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  6683. }
  6684. } else if (evt.type === 'done') {
  6685. 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');
  6686. }
  6687. }
  6688. async function executeTraceroute(e) {
  6689. if (e) e.preventDefault();
  6690. if (tracerouteAbortController) {
  6691. tracerouteAbortController.abort();
  6692. tracerouteAbortController = null;
  6693. resetTracerouteButton();
  6694. showToast('Traceroute Stopped', 'Traceroute stopped by user', 'info');
  6695. return;
  6696. }
  6697. const target = document.getElementById('tools-tr-target')?.value?.trim();
  6698. const maxHops = parseInt(document.getElementById('tools-tr-maxhops')?.value || '15', 10);
  6699. const protocol = document.getElementById('tools-tr-proto')?.value || 'icmp';
  6700. const iface = document.getElementById('tools-tr-iface')?.value || '';
  6701. const resolve = document.getElementById('tools-tr-resolve')?.checked || false;
  6702. if (!target) {
  6703. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  6704. return;
  6705. }
  6706. clearTracerouteTable();
  6707. const resCard = document.getElementById('tools-tr-results');
  6708. if (resCard) resCard.classList.remove('hidden');
  6709. tracerouteAbortController = new AbortController();
  6710. setTracerouteRunningButton();
  6711. try {
  6712. const res = await fetch(`${API_BASE}/tools/traceroute/stream`, {
  6713. method: 'POST',
  6714. headers: { 'Content-Type': 'application/json' },
  6715. body: JSON.stringify({
  6716. target,
  6717. max_hops: maxHops,
  6718. protocol,
  6719. interface: iface,
  6720. resolve
  6721. }),
  6722. signal: tracerouteAbortController.signal
  6723. });
  6724. if (!res.ok) {
  6725. const errText = await res.text();
  6726. showToast('Traceroute Error', errText || 'Failed to start traceroute', 'error');
  6727. resetTracerouteButton();
  6728. tracerouteAbortController = null;
  6729. return;
  6730. }
  6731. const reader = res.body.getReader();
  6732. const decoder = new TextDecoder('utf-8');
  6733. let buffer = '';
  6734. while (true) {
  6735. const { done, value } = await reader.read();
  6736. if (done) break;
  6737. buffer += decoder.decode(value, { stream: true });
  6738. const blocks = buffer.split('\n\n');
  6739. buffer = blocks.pop() || '';
  6740. for (const block of blocks) {
  6741. const trimmed = block.trim();
  6742. if (!trimmed) continue;
  6743. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  6744. try {
  6745. const evt = JSON.parse(line);
  6746. handleLiveTracerouteEvent(evt);
  6747. } catch (parseErr) {
  6748. console.warn('Traceroute SSE parse error:', parseErr, line);
  6749. }
  6750. }
  6751. }
  6752. } catch (err) {
  6753. if (err.name === 'AbortError') {
  6754. // User aborted normally
  6755. } else {
  6756. showToast('Traceroute Error', err.message, 'error');
  6757. }
  6758. } finally {
  6759. tracerouteAbortController = null;
  6760. resetTracerouteButton();
  6761. }
  6762. }
  6763. function handleLiveTracerouteEvent(evt) {
  6764. const statHops = document.getElementById('tools-tr-hops-count');
  6765. const tbody = document.getElementById('tools-tr-tbody');
  6766. const rawEl = document.getElementById('tools-tr-raw');
  6767. if (evt.raw && rawEl) {
  6768. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  6769. rawEl.scrollTop = rawEl.scrollHeight;
  6770. }
  6771. if (evt.hops_count !== undefined && statHops) {
  6772. statHops.innerText = `${evt.hops_count} Hops`;
  6773. }
  6774. if (evt.type === 'hop' && evt.hop && tbody) {
  6775. const h = evt.hop;
  6776. const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
  6777. const rtt1 = Array.isArray(h.times_ms) && h.times_ms[0] ? `${h.times_ms[0]} ms` : (isTimeout ? '*' : '--');
  6778. const rtt2 = Array.isArray(h.times_ms) && h.times_ms[1] ? `${h.times_ms[1]} ms` : (isTimeout ? '*' : '--');
  6779. const displayHost = h.host && h.host !== h.ip ? `${escapeHtml(h.host)} (${escapeHtml(h.ip || '')})` : escapeHtml(h.ip || (isTimeout ? 'Request timed out' : '--'));
  6780. const tr = document.createElement('tr');
  6781. tr.className = `hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}`;
  6782. tr.innerHTML = `
  6783. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  6784. <td class="py-2.5 px-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${displayHost}</td>
  6785. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt1)}</td>
  6786. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt2)}</td>
  6787. <td class="py-2.5 px-3 text-right">
  6788. ${isTimeout
  6789. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
  6790. : '<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>'}
  6791. </td>
  6792. `;
  6793. tbody.appendChild(tr);
  6794. } else if (evt.type === 'done') {
  6795. showToast('Traceroute Finished', `Traced ${evt.hops_count || 0} hops`, 'info');
  6796. }
  6797. }
  6798. async function executeMTR(e) {
  6799. if (e) e.preventDefault();
  6800. const target = document.getElementById('tools-mtr-target')?.value?.trim();
  6801. const cycles = parseInt(document.getElementById('tools-mtr-count')?.value || '3', 10);
  6802. if (!target) {
  6803. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  6804. return;
  6805. }
  6806. const btn = document.getElementById('tools-mtr-btn');
  6807. const spinner = document.getElementById('tools-mtr-spinner');
  6808. if (btn) btn.disabled = true;
  6809. if (spinner) spinner.classList.remove('hidden');
  6810. try {
  6811. const res = await fetch(`${API_BASE}/tools/mtr`, {
  6812. method: 'POST',
  6813. headers: { 'Content-Type': 'application/json' },
  6814. body: JSON.stringify({ target, count: cycles })
  6815. });
  6816. const data = await res.json();
  6817. if (!res.ok) {
  6818. showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
  6819. return;
  6820. }
  6821. const resCard = document.getElementById('tools-mtr-results');
  6822. if (resCard) resCard.classList.remove('hidden');
  6823. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  6824. const statHops = document.getElementById('tools-mtr-hops-count');
  6825. if (statHops) statHops.innerText = `${hopsCount} Hops`;
  6826. const tbody = document.getElementById('tools-mtr-tbody');
  6827. if (tbody) {
  6828. if (hopsCount > 0) {
  6829. tbody.innerHTML = data.hops.map(h => {
  6830. 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');
  6831. return `
  6832. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  6833. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  6834. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
  6835. <td class="py-2.5 px-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
  6836. <td class="py-2.5 px-3 text-slate-300">${h.sent}</td>
  6837. <td class="py-2.5 px-3 text-slate-300">${h.last_ms.toFixed(1)}</td>
  6838. <td class="py-2.5 px-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)}</td>
  6839. <td class="py-2.5 px-3 text-emerald-400">${h.best_ms.toFixed(1)}</td>
  6840. <td class="py-2.5 px-3 text-rose-400">${h.wrst_ms.toFixed(1)}</td>
  6841. <td class="py-2.5 px-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
  6842. </tr>
  6843. `;
  6844. }).join('');
  6845. } else {
  6846. tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
  6847. }
  6848. }
  6849. const rawEl = document.getElementById('tools-mtr-raw');
  6850. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  6851. showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
  6852. } catch (err) {
  6853. showToast('MTR Error', err.message, 'error');
  6854. } finally {
  6855. if (btn) btn.disabled = false;
  6856. if (spinner) spinner.classList.add('hidden');
  6857. }
  6858. }
  6859. async function executeDNS(e) {
  6860. if (e) e.preventDefault();
  6861. const domain = document.getElementById('tools-dns-domain')?.value?.trim();
  6862. const type = document.getElementById('tools-dns-type')?.value || 'A';
  6863. const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
  6864. if (!domain) {
  6865. showToast('Input Required', 'Please enter a hostname or domain', 'warning');
  6866. return;
  6867. }
  6868. const btn = document.getElementById('tools-dns-btn');
  6869. const spinner = document.getElementById('tools-dns-spinner');
  6870. if (btn) btn.disabled = true;
  6871. if (spinner) spinner.classList.remove('hidden');
  6872. try {
  6873. const res = await fetch(`${API_BASE}/tools/dns`, {
  6874. method: 'POST',
  6875. headers: { 'Content-Type': 'application/json' },
  6876. body: JSON.stringify({ domain, type, server })
  6877. });
  6878. const data = await res.json();
  6879. if (!res.ok) {
  6880. showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
  6881. return;
  6882. }
  6883. const resCard = document.getElementById('tools-dns-results');
  6884. if (resCard) resCard.classList.remove('hidden');
  6885. const metaEl = document.getElementById('tools-dns-meta');
  6886. if (metaEl) metaEl.innerText = `Resolved in ${data.query_time_ms ?? 0} ms via ${escapeHtml(data.server || 'System DNS')}`;
  6887. const tbody = document.getElementById('tools-dns-tbody');
  6888. if (tbody) {
  6889. if (Array.isArray(data.records) && data.records.length > 0) {
  6890. tbody.innerHTML = data.records.map(r => `
  6891. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  6892. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.name)}</td>
  6893. <td class="py-2.5 px-3 text-slate-400">${r.ttl}s</td>
  6894. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.class || 'IN')}</td>
  6895. <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>
  6896. <td class="py-2.5 px-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
  6897. </tr>
  6898. `).join('');
  6899. } else {
  6900. 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>`;
  6901. }
  6902. }
  6903. const rawEl = document.getElementById('tools-dns-raw');
  6904. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  6905. showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
  6906. } catch (err) {
  6907. showToast('DNS Error', err.message, 'error');
  6908. } finally {
  6909. if (btn) btn.disabled = false;
  6910. if (spinner) spinner.classList.add('hidden');
  6911. }
  6912. }
  6913. async function executePortProbe(e) {
  6914. if (e) e.preventDefault();
  6915. const target = document.getElementById('tools-port-target')?.value?.trim();
  6916. const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
  6917. const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
  6918. if (!target || !port) {
  6919. showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
  6920. return;
  6921. }
  6922. const btn = document.getElementById('tools-port-btn');
  6923. const spinner = document.getElementById('tools-port-spinner');
  6924. if (btn) btn.disabled = true;
  6925. if (spinner) spinner.classList.remove('hidden');
  6926. try {
  6927. const res = await fetch(`${API_BASE}/tools/port-probe`, {
  6928. method: 'POST',
  6929. headers: { 'Content-Type': 'application/json' },
  6930. body: JSON.stringify({ target, port, timeout })
  6931. });
  6932. const data = await res.json();
  6933. if (!res.ok) {
  6934. showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
  6935. return;
  6936. }
  6937. const resCard = document.getElementById('tools-port-results');
  6938. if (resCard) resCard.classList.remove('hidden');
  6939. const banner = document.getElementById('tools-port-banner');
  6940. const icon = document.getElementById('tools-port-icon');
  6941. const title = document.getElementById('tools-port-title');
  6942. const sub = document.getElementById('tools-port-sub');
  6943. const latency = document.getElementById('tools-port-latency');
  6944. if (data.open) {
  6945. if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
  6946. if (icon) {
  6947. 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';
  6948. icon.innerText = '✓';
  6949. }
  6950. if (title) {
  6951. title.className = 'text-sm font-bold text-emerald-300';
  6952. title.innerText = `PORT ${port} OPEN / LISTENING`;
  6953. }
  6954. if (sub) {
  6955. sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
  6956. sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
  6957. }
  6958. if (latency) {
  6959. latency.className = 'text-base font-bold font-mono text-emerald-300';
  6960. latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
  6961. }
  6962. } else {
  6963. if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-800/50 flex items-center justify-between';
  6964. if (icon) {
  6965. 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';
  6966. icon.innerText = '✕';
  6967. }
  6968. if (title) {
  6969. title.className = 'text-sm font-bold text-rose-300';
  6970. title.innerText = `PORT ${port} CLOSED / FILTERED`;
  6971. }
  6972. if (sub) {
  6973. sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
  6974. sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
  6975. }
  6976. if (latency) {
  6977. latency.className = 'text-base font-bold font-mono text-slate-500';
  6978. latency.innerText = '--';
  6979. }
  6980. }
  6981. const rawEl = document.getElementById('tools-port-raw');
  6982. 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'}`);
  6983. showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
  6984. } catch (err) {
  6985. showToast('Probe Error', err.message, 'error');
  6986. } finally {
  6987. if (btn) btn.disabled = false;
  6988. if (spinner) spinner.classList.add('hidden');
  6989. }
  6990. }