app.js 283 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731
  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. };
  44. const API_BASE = '/api';
  45. function escapeHtml(str) {
  46. if (str === null || str === undefined) return '';
  47. return String(str)
  48. .replace(/&/g, '&')
  49. .replace(/</g, '&lt;')
  50. .replace(/>/g, '&gt;')
  51. .replace(/"/g, '&quot;')
  52. .replace(/'/g, '&#039;');
  53. }
  54. // Initialize on page load
  55. document.addEventListener('DOMContentLoaded', () => {
  56. const hash = window.location.hash.replace('#', '') || 'dashboard';
  57. navigate(hash);
  58. fetchData();
  59. // Live polling every 2.5 seconds
  60. setInterval(() => {
  61. if (state.isPolling) {
  62. fetchData(false);
  63. }
  64. }, 2500);
  65. });
  66. // Navigation Handler
  67. function navigate(tabName) {
  68. if (tabName === 'dynamic-routing' || tabName === 'routing') {
  69. navigate('bgp');
  70. return;
  71. }
  72. state.activeTab = tabName;
  73. window.location.hash = tabName;
  74. // Update nav links styling
  75. document.querySelectorAll('.nav-link').forEach(link => {
  76. 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';
  77. });
  78. const activeNav = document.getElementById(`nav-${tabName}`);
  79. if (activeNav) {
  80. 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';
  81. }
  82. // Update page headers
  83. const titles = {
  84. dashboard: { title: 'Dashboard Overview', sub: 'Live router performance and network telemetry' },
  85. interfaces: { title: 'Network Interfaces', sub: 'Hierarchical view of physical interfaces and nested 802.1Q VLANs' },
  86. bridge: { title: 'Bridge Interfaces', sub: 'MikroTik-style IEEE 802.1D / 802.1Q VLAN Filtering Bridge with RSTP & FDB' },
  87. vlans: { title: 'VLAN Virtual Networks', sub: 'IEEE 802.1Q sub-interface segmentation and routing' },
  88. firewall: { title: 'MikroTik Firewall', sub: 'Filter rules, NAT, Mangle, Address Lists & Active Connections tracking' },
  89. routes: { title: 'Routing & Policy', sub: 'Routing tables, static routes (DAS/DAC), and policy routing rules' },
  90. bgp: { title: 'BGP Routing (/routing bgp)', sub: 'FRRouting BGP peering sessions, advertised networks, and BGP routing table (RIB)' },
  91. ospf: { title: 'OSPF Routing (/routing ospf)', sub: 'FRRouting OSPFv2 link-state routing, dynamic neighbor adjacencies, and multi-area topology' },
  92. 'dynamic-routing': { title: 'BGP Routing (/routing bgp)', sub: 'FRRouting dynamic routing' },
  93. ppp: { title: 'PPP Servers & Secrets', sub: 'MikroTik RouterOS user accounts, IP pools and VPN server concentrators' },
  94. eoip: { title: 'EoIP Tunnels', sub: 'Ethernet over IP Layer 2 tunneling (MikroTik RouterOS style)' },
  95. pppoe: { title: 'PPPoE Client WAN', sub: 'Point-to-Point Protocol over Ethernet WAN access' },
  96. wireguard: { title: 'WireGuard Kernel VPN', sub: 'Modern ultra-fast cryptographic VPN tunnel manager' },
  97. ipsec: { title: 'IPSec (IKEv2) strongSwan', sub: 'Enterprise Site-to-Site & Roadwarrior IPSec controller' },
  98. l2tp: { title: 'L2TP VPN Client', sub: 'Layer 2 Tunneling Protocol via xl2tpd' },
  99. pptp: { title: 'PPTP VPN Client', sub: 'Point-to-Point Tunneling Protocol with MPPE-128 encryption' },
  100. persistence: { title: 'Debian Configuration', sub: 'Native /etc/network/interfaces.d/ persistence manager' }
  101. };
  102. const header = titles[tabName] || titles.dashboard;
  103. const pTitle = document.getElementById('page-title');
  104. if (pTitle) pTitle.innerText = header.title;
  105. const pSub = document.getElementById('page-subtitle');
  106. if (pSub) pSub.innerText = header.sub;
  107. // Toggle sections dynamically for all section elements
  108. document.querySelectorAll('main section[id^="section-"]').forEach(el => {
  109. if (el.id === `section-${tabName}`) {
  110. el.classList.remove('hidden');
  111. } else {
  112. el.classList.add('hidden');
  113. }
  114. });
  115. if (tabName === 'bridge') loadBridge();
  116. if (tabName === 'firewall') loadFirewall();
  117. if (tabName === 'routes') loadRoutes();
  118. if (tabName === 'bgp') {
  119. loadDynamicRouting();
  120. switchBgpSubTab(state.activeBgpSubTab || 'bgp-peers');
  121. }
  122. if (tabName === 'ospf') {
  123. loadDynamicRouting();
  124. switchOspfSubTab(state.activeOspfSubTab || 'ospf-ifaces');
  125. }
  126. if (tabName === 'dynamic-routing') loadDynamicRouting();
  127. if (tabName === 'ppp') loadPPP();
  128. if (tabName === 'eoip') loadEoIP();
  129. if (tabName === 'persistence') loadDebianConfig();
  130. if (tabName === 'pppoe') loadPPPoE();
  131. if (tabName === 'wireguard') loadWireGuard();
  132. if (tabName === 'ipsec') loadIPSec();
  133. if (tabName === 'l2tp') loadL2TP();
  134. if (tabName === 'pptp') loadPPTP();
  135. }
  136. // Fetch all core system, network and VPN telemetry
  137. async function fetchData(isManual = false) {
  138. const spinner = document.getElementById('refresh-spinner');
  139. if (isManual && spinner) spinner.classList.add('animate-spin');
  140. try {
  141. const [statusRes, ifacesRes, vlansRes, vpnRes, fwRes, dynRes, brSummaryRes] = await Promise.all([
  142. fetch(`${API_BASE}/system/status`),
  143. fetch(`${API_BASE}/interfaces`),
  144. fetch(`${API_BASE}/vlans`),
  145. fetch(`${API_BASE}/vpn/status`),
  146. fetch(`${API_BASE}/firewall/summary`),
  147. fetch(`${API_BASE}/routing/dynamic/summary`),
  148. fetch(`${API_BASE}/bridge/summary`)
  149. ]);
  150. if (brSummaryRes.ok) {
  151. state.bridgeSummary = await brSummaryRes.json();
  152. const bBridge = document.getElementById('badge-bridge-count');
  153. if (bBridge) bBridge.innerText = state.bridgeSummary?.bridges_count || 0;
  154. const sBr = document.getElementById('bridge-stat-bridges');
  155. if (sBr) sBr.innerText = state.bridgeSummary?.bridges_count || 0;
  156. const sPorts = document.getElementById('bridge-stat-ports');
  157. if (sPorts) sPorts.innerText = state.bridgeSummary?.ports_count || 0;
  158. const sHosts = document.getElementById('bridge-stat-hosts');
  159. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  160. }
  161. if (statusRes.ok) state.systemStatus = await statusRes.json();
  162. if (ifacesRes.ok) {
  163. const ifacesData = await ifacesRes.json();
  164. const rawIfaces = Array.isArray(ifacesData) ? ifacesData : [];
  165. state.interfaces = rawIfaces.filter(i => {
  166. if (!i.name) return false;
  167. if (i.name.startsWith('ep_')) return false;
  168. return !['gre0', 'gretap0', 'erspan0', 'sit0', 'tunl0', 'ip6tnl0', 'ip6gre0', 'ip6erspan0'].includes(i.name);
  169. });
  170. }
  171. if (vlansRes.ok) {
  172. const vlansData = await vlansRes.json();
  173. state.vlans = Array.isArray(vlansData) ? vlansData : [];
  174. }
  175. if (vpnRes.ok) state.vpnStatus = await vpnRes.json();
  176. if (fwRes && fwRes.ok) state.fwSummary = await fwRes.json();
  177. if (dynRes && dynRes.ok) state.dynSummary = await dynRes.json();
  178. updateSystemMetrics();
  179. updateBadges();
  180. if (state.activeTab === 'dashboard') renderDashboard();
  181. if (state.activeTab === 'interfaces') renderInterfacesList();
  182. if (state.activeTab === 'vlans') renderVlansList();
  183. if (state.activeTab === 'firewall') loadFirewall(false);
  184. if (state.activeTab === 'routes') loadRoutes(false);
  185. if (state.activeTab === 'dynamic-routing' || state.activeTab === 'bgp' || state.activeTab === 'ospf') loadDynamicRouting(false);
  186. if (state.activeTab === 'ppp') loadPPP(false);
  187. if (state.activeTab === 'eoip') loadEoIP(false);
  188. if (state.activeTab === 'pppoe') loadPPPoE(false);
  189. if (state.activeTab === 'wireguard') loadWireGuard(false);
  190. if (state.activeTab === 'ipsec') loadIPSec(false);
  191. if (state.activeTab === 'l2tp') loadL2TP(false);
  192. if (state.activeTab === 'pptp') loadPPTP(false);
  193. } catch (err) {
  194. console.error('Failed to fetch router state:', err);
  195. } finally {
  196. if (isManual && spinner) {
  197. setTimeout(() => spinner.classList.remove('animate-spin'), 300);
  198. }
  199. }
  200. }
  201. // Update Top KPI and Sidebar Telemetry
  202. function updateSystemMetrics() {
  203. const s = state.systemStatus;
  204. const v = state.vpnStatus;
  205. if (!s) return;
  206. // Sidebar
  207. document.getElementById('side-hostname').innerText = s.hostname || 'debian-lxc';
  208. document.getElementById('side-uptime').innerText = s.uptime_human || '0m';
  209. document.getElementById('side-gateway-ip').innerText = s.default_gateway ? `GW: ${s.default_gateway}` : 'GW: Isolated';
  210. if (s.cpu_pct !== undefined) {
  211. const pct = s.cpu_pct;
  212. document.getElementById('side-cpu-val').innerText = `${pct.toFixed(1)}%`;
  213. document.getElementById('side-cpu-bar').style.width = `${Math.max(4, Math.min(100, pct))}%`;
  214. const loadStr = s.cpu_load ? s.cpu_load.join(', ') : '-';
  215. document.getElementById('side-cpu-bar').title = `Container: ${pct}% | Host Loadavg: ${loadStr} (${s.cpu_cores || 1} cores)`;
  216. } else if (s.cpu_load && s.cpu_load.length > 0) {
  217. const cores = s.cpu_cores || 4;
  218. const pct = Math.min(100, Math.round((parseFloat(s.cpu_load[0]) / cores) * 100));
  219. document.getElementById('side-cpu-val').innerText = `${pct}%`;
  220. document.getElementById('side-cpu-bar').style.width = `${Math.max(4, pct)}%`;
  221. }
  222. document.getElementById('side-ram-val').innerText = `${Math.round(s.mem_usage_pct || 0)}%`;
  223. document.getElementById('side-ram-bar').style.width = `${Math.max(5, Math.round(s.mem_usage_pct || 0))}%`;
  224. // Dashboard Stats
  225. document.getElementById('stat-ifaces-up').innerText = s.up_ifaces || 0;
  226. document.getElementById('stat-ifaces-total').innerText = `${s.total_ifaces || 0} Total`;
  227. document.getElementById('stat-ifaces-down').innerText = `${s.down_ifaces || 0} DOWN`;
  228. document.getElementById('stat-vlans-count').innerText = s.vlan_ifaces || 0;
  229. // VPN Status Indicators
  230. if (v) {
  231. const totalActive = v.total_active_tunnels || 0;
  232. const statVpnActive = document.getElementById('stat-vpn-active');
  233. if (statVpnActive) statVpnActive.innerText = totalActive;
  234. const tunnelsDot = document.getElementById('tunnels-dot');
  235. const tunnelsLabel = document.getElementById('tunnels-label');
  236. if (tunnelsDot && tunnelsLabel) {
  237. if (totalActive > 0) {
  238. tunnelsDot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  239. tunnelsLabel.innerText = `${totalActive} Active VPN Tunnel${totalActive > 1 ? 's' : ''}`;
  240. } else {
  241. tunnelsDot.className = 'w-2 h-2 rounded-full bg-slate-500';
  242. tunnelsLabel.innerText = '0 Active VPN Tunnels';
  243. }
  244. }
  245. setDotBadge('badge-pppoe-status', (v.active_pppoe || 0) > 0 || v.pppoe_connected);
  246. setDotBadge('badge-wg-status', (v.active_wireguard || 0) > 0 || v.wireguard_active);
  247. setDotBadge('badge-ipsec-status', (v.active_ipsec || 0) > 0 || v.ipsec_active);
  248. setDotBadge('badge-l2tp-status', (v.active_l2tp || 0) > 0 || v.l2tp_connected);
  249. setDotBadge('badge-pptp-status', (v.active_pptp || 0) > 0 || v.pptp_connected);
  250. }
  251. // Total Live Bandwidth Rate
  252. let totalRx = 0;
  253. let totalTx = 0;
  254. (state.interfaces || []).forEach(i => {
  255. if (i.rate) {
  256. totalRx += i.rate.rx_bytes_sec || 0;
  257. totalTx += i.rate.tx_bytes_sec || 0;
  258. }
  259. });
  260. document.getElementById('stat-traffic-rx').innerText = formatTraffic(totalRx);
  261. document.getElementById('stat-traffic-tx').innerText = formatTraffic(totalTx);
  262. }
  263. function setDotBadge(id, active) {
  264. const el = document.getElementById(id);
  265. if (!el) return;
  266. if (active) {
  267. el.className = 'w-2 h-2 rounded-full bg-emerald-400 shadow-sm shadow-emerald-400/80';
  268. } else {
  269. el.className = 'w-2 h-2 rounded-full bg-slate-600';
  270. }
  271. }
  272. function updateBadges() {
  273. const bIfaces = document.getElementById('badge-ifaces-count');
  274. if (bIfaces) bIfaces.innerText = (state.interfaces || []).length;
  275. const bVlans = document.getElementById('badge-vlans-count');
  276. if (bVlans) bVlans.innerText = (state.vlans || []).length;
  277. if (state.fwSummary) {
  278. const totalFwRules = (state.fwSummary.filter_rules_count || 0) + (state.fwSummary.nat_rules_count || 0) + (state.fwSummary.mangle_rules_count || 0);
  279. const badgeFw = document.getElementById('badge-firewall-count');
  280. if (badgeFw) badgeFw.innerText = totalFwRules;
  281. }
  282. if (state.vpnStatus) {
  283. const v = state.vpnStatus;
  284. const bEoIP = document.getElementById('badge-eoip-count');
  285. if (bEoIP) bEoIP.innerText = v.total_eoip || 0;
  286. const bPPPSess = document.getElementById('badge-ppp-sessions');
  287. if (bPPPSess) bPPPSess.innerText = v.total_ppp_sessions || 0;
  288. setDotBadge('badge-pppoe-status', v.active_pppoe > 0 || v.pppoe_server_running);
  289. setDotBadge('badge-wg-status', v.active_wireguard > 0);
  290. setDotBadge('badge-ipsec-status', v.active_ipsec > 0 || v.ipsec_server_running);
  291. setDotBadge('badge-l2tp-status', v.active_l2tp > 0 || v.l2tp_server_running);
  292. setDotBadge('badge-pptp-status', v.active_pptp > 0 || v.pptp_server_running);
  293. }
  294. if (state.dynSummary) {
  295. const d = state.dynSummary;
  296. setDotBadge('badge-bgp-dot', d.bgp_running);
  297. setDotBadge('badge-ospf-dot', d.ospf_running);
  298. const bBgp = document.getElementById('badge-bgp-count');
  299. if (bBgp) bBgp.innerText = (state.bgpPeers || []).length;
  300. const bOspf = document.getElementById('badge-ospf-count');
  301. if (bOspf) bOspf.innerText = (state.ospfInterfaces || []).length;
  302. }
  303. }
  304. // Render Dashboard View
  305. function renderDashboard() {
  306. const matrix = document.getElementById('port-matrix');
  307. matrix.innerHTML = '';
  308. (state.interfaces || []).forEach(iface => {
  309. const isUp = iface.state === 'UP';
  310. const isVlan = iface.is_vlan;
  311. const portCard = document.createElement('div');
  312. portCard.className = `p-3 rounded-xl border transition-all cursor-pointer select-none group ${
  313. isUp
  314. ? (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')
  315. : 'bg-slate-900/40 border-slate-800/60 opacity-60 hover:opacity-100 hover:border-slate-700'
  316. }`;
  317. portCard.onclick = () => openIfaceModal(iface.name);
  318. let statusPillClass = isUp ? 'bg-emerald-500 shadow-sm shadow-emerald-500/50' : 'bg-rose-500';
  319. if (isVlan) statusPillClass = isUp ? 'bg-cyan-400 shadow-sm shadow-cyan-400/50' : 'bg-rose-500';
  320. portCard.innerHTML = `
  321. <div class="flex items-center justify-between mb-2">
  322. <span class="font-bold text-xs font-mono text-white group-hover:text-brand-400 transition truncate">${iface.name}</span>
  323. <span class="w-2 h-2 rounded-full ${statusPillClass}"></span>
  324. </div>
  325. <div class="text-[11px] font-mono text-slate-300 truncate">${iface.ipv4 && iface.ipv4.length > 0 ? iface.ipv4[0] : (iface.mac || 'No IP')}</div>
  326. <div class="mt-2 flex items-center justify-between text-[10px] text-slate-400">
  327. <span class="uppercase tracking-wider font-semibold">${isVlan ? `VLAN ${iface.vlan_id}` : iface.type}</span>
  328. <span>${iface.rate?.rx_human || '0 B/s'}</span>
  329. </div>
  330. `;
  331. matrix.appendChild(portCard);
  332. });
  333. const ifaceTbody = document.getElementById('quick-interfaces-table');
  334. ifaceTbody.innerHTML = '';
  335. (state.interfaces || []).slice(0, 6).forEach(i => {
  336. const isUp = i.state === 'UP';
  337. const tr = document.createElement('tr');
  338. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  339. tr.onclick = () => openIfaceModal(i.name);
  340. tr.innerHTML = `
  341. <td class="py-2.5 font-bold text-white flex items-center gap-2">
  342. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  343. <span>${i.name}</span>
  344. </td>
  345. <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>
  346. <td class="py-2.5 text-slate-300">${i.ipv4 && i.ipv4.length > 0 ? i.ipv4[0] : '<span class="text-slate-600">-</span>'}</td>
  347. <td class="py-2.5 text-right font-sans font-semibold ${isUp ? 'text-emerald-400' : 'text-rose-400'}">${i.state}</td>
  348. `;
  349. ifaceTbody.appendChild(tr);
  350. });
  351. const vlanTbody = document.getElementById('quick-vlans-table');
  352. vlanTbody.innerHTML = '';
  353. const vlans = state.vlans || [];
  354. if (vlans.length === 0) {
  355. 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>`;
  356. } else {
  357. vlans.slice(0, 6).forEach(v => {
  358. const tr = document.createElement('tr');
  359. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  360. tr.onclick = () => openIfaceModal(v.name);
  361. tr.innerHTML = `
  362. <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>
  363. <td class="py-2.5 text-white font-bold">${v.name}</td>
  364. <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>
  365. <td class="py-2.5 text-right text-slate-400">${v.parent_name || 'eth0'}</td>
  366. `;
  367. vlanTbody.appendChild(tr);
  368. });
  369. }
  370. }
  371. // Expand / Collapse Handlers
  372. function toggleExpand(parentName) {
  373. if (state.expandedParents.has(parentName)) {
  374. state.expandedParents.delete(parentName);
  375. } else {
  376. state.expandedParents.add(parentName);
  377. }
  378. renderInterfacesList();
  379. }
  380. function expandAllIfaces(expand) {
  381. if (expand) {
  382. (state.interfaces || []).forEach(i => {
  383. if (!i.is_vlan) state.expandedParents.add(i.name);
  384. });
  385. } else {
  386. state.expandedParents.clear();
  387. }
  388. renderInterfacesList();
  389. }
  390. // Filter and Render Hierarchical Interfaces List
  391. function filterIfaces(filter) {
  392. state.ifaceFilter = filter;
  393. document.querySelectorAll('.filter-btn').forEach(btn => {
  394. 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';
  395. });
  396. const activeBtn = document.getElementById(`filter-${filter}`);
  397. if (activeBtn) {
  398. activeBtn.className = 'filter-btn px-3 py-1.5 rounded-lg text-xs font-medium bg-slate-800 text-white border border-slate-700';
  399. }
  400. renderInterfacesList();
  401. }
  402. function renderInterfacesList() {
  403. const tbody = document.getElementById('interfaces-tree-tbody');
  404. const emptyState = document.getElementById('interfaces-empty-state');
  405. const summary = document.getElementById('ifaces-list-summary');
  406. const query = (document.getElementById('iface-search')?.value || '').toLowerCase();
  407. tbody.innerHTML = '';
  408. const allIfaces = state.interfaces || [];
  409. const allVlans = state.vlans || [];
  410. const parentIfaces = allIfaces.filter(i => !i.is_vlan);
  411. const filteredParents = parentIfaces.filter(parent => {
  412. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  413. if (query) {
  414. const matchParent = parent.name.toLowerCase().includes(query) || (parent.role || '').toLowerCase().includes(query);
  415. const matchVlan = childVlans.some(v => v.name.toLowerCase().includes(query) || String(v.vlan_id).includes(query) || (v.description || '').toLowerCase().includes(query));
  416. if (!matchParent && !matchVlan) return false;
  417. }
  418. if (state.ifaceFilter === 'has_vlans') return childVlans.length > 0;
  419. if (state.ifaceFilter === 'physical') return parent.type !== 'loopback';
  420. if (state.ifaceFilter === 'up') return parent.state === 'UP';
  421. return true;
  422. });
  423. if (summary) {
  424. summary.innerText = `${parentIfaces.length} Physical/Parent Links • ${allVlans.length} Active VLANs`;
  425. }
  426. if (filteredParents.length === 0) {
  427. emptyState?.classList.remove('hidden');
  428. return;
  429. }
  430. emptyState?.classList.add('hidden');
  431. filteredParents.forEach(parent => {
  432. const isUp = parent.state === 'UP';
  433. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  434. const isExpanded = state.expandedParents.has(parent.name);
  435. const parentRow = document.createElement('tr');
  436. parentRow.className = `hover:bg-slate-800/50 transition border-b border-slate-800/80 ${isExpanded ? 'bg-slate-900/80' : ''}`;
  437. parentRow.innerHTML = `
  438. <td class="py-3 px-3 text-center">
  439. <button onclick="toggleExpand('${parent.name}')" title="${isExpanded ? 'Collapse VLANs' : 'Expand VLANs'}"
  440. class="w-6 h-6 rounded flex items-center justify-center hover:bg-slate-800 text-slate-400 hover:text-white transition">
  441. <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">
  442. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M9 5l7 7-7 7" />
  443. </svg>
  444. </button>
  445. </td>
  446. <td class="py-3 px-4">
  447. <div class="flex items-center space-x-2.5">
  448. <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">
  449. ${parent.type === 'loopback' ? 'LO' : 'NIC'}
  450. </div>
  451. <div>
  452. <div class="flex items-center gap-2">
  453. <span class="font-bold text-white text-sm cursor-pointer hover:text-cyan-400" onclick="toggleExpand('${parent.name}')">${parent.name}</span>
  454. ${childVlans.length > 0
  455. ? `<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>`
  456. : `<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>`
  457. }
  458. </div>
  459. <div class="text-[10px] text-slate-500 font-sans mt-0.5">${parent.type}</div>
  460. </div>
  461. </div>
  462. </td>
  463. <td class="py-3 px-4 font-sans">
  464. <div class="flex items-center gap-1.5">
  465. <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>
  466. <span class="text-xs text-slate-400 truncate max-w-[120px]">${parent.description || '-'}</span>
  467. </div>
  468. </td>
  469. <td class="py-3 px-4">
  470. ${parent.ipv4 && parent.ipv4.length > 0
  471. ? `<div class="text-white font-medium">${parent.ipv4[0]}</div>`
  472. : '<span class="text-slate-600 font-sans">Unassigned</span>'
  473. }
  474. </td>
  475. <td class="py-3 px-4 text-slate-400 text-[11px]">
  476. <div>${parent.mac || 'N/A'}</div>
  477. <div class="text-[10px] text-slate-500">MTU ${parent.mtu}</div>
  478. </td>
  479. <td class="py-3 px-4 text-[11px]">
  480. <div class="flex items-center space-x-2">
  481. <span class="text-emerald-400">↓ ${parent.rate?.rx_human || '0 B/s'}</span>
  482. <span class="text-cyan-400">↑ ${parent.rate?.tx_human || '0 B/s'}</span>
  483. </div>
  484. </td>
  485. <td class="py-3 px-4 font-sans">
  486. <button onclick="toggleInterfaceState('${parent.name}', '${isUp ? 'down' : 'up'}')"
  487. class="flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full transition ${
  488. 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'
  489. }" title="Click to toggle link status">
  490. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  491. <span>${parent.state}</span>
  492. </button>
  493. </td>
  494. <td class="py-3 px-4 text-right space-x-2 font-sans">
  495. <button onclick="openVlanModal('${parent.name}')"
  496. 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">
  497. + Add VLAN
  498. </button>
  499. <button onclick="openIfaceModal('${parent.name}')"
  500. 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">
  501. Configure
  502. </button>
  503. </td>
  504. `;
  505. tbody.appendChild(parentRow);
  506. if (isExpanded) {
  507. const drawerRow = document.createElement('tr');
  508. drawerRow.className = 'bg-slate-950/80 border-b border-slate-800/90';
  509. const drawerCell = document.createElement('td');
  510. drawerCell.colSpan = 8;
  511. drawerCell.className = 'p-0';
  512. drawerCell.innerHTML = `
  513. <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">
  514. <div class="flex items-center justify-between mb-3">
  515. <div class="flex items-center space-x-3">
  516. <span class="font-bold text-xs text-white uppercase tracking-wider flex items-center gap-1.5 font-sans">
  517. <span>VLAN Sub-interfaces on <code class="text-cyan-300 lowercase">${parent.name}</code></span>
  518. </span>
  519. <span class="text-[11px] bg-cyan-950 text-cyan-400 px-2 py-0.5 rounded-full border border-cyan-800/60 font-mono">
  520. ${childVlans.length} Attached
  521. </span>
  522. </div>
  523. <button onclick="openVlanModal('${parent.name}')"
  524. 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">
  525. <span>+ Create VLAN on ${parent.name}</span>
  526. </button>
  527. </div>
  528. ${childVlans.length === 0 ? `
  529. <div class="p-6 text-center border border-dashed border-slate-800 rounded-xl bg-slate-900/40 font-sans">
  530. <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>
  531. <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">
  532. <span>+ Create Your First VLAN on ${parent.name}</span>
  533. </button>
  534. </div>
  535. ` : `
  536. <div class="overflow-x-auto rounded-lg border border-slate-800 bg-slate-900/90 shadow-inner">
  537. <table class="w-full text-left text-xs font-mono">
  538. <thead class="text-slate-400 bg-slate-950/70 border-b border-slate-800 uppercase tracking-wider text-[10px] font-sans">
  539. <tr>
  540. <th class="py-2.5 px-4">VLAN ID</th>
  541. <th class="py-2.5 px-4">Interface Device</th>
  542. <th class="py-2.5 px-4">Subnet Gateway</th>
  543. <th class="py-2.5 px-4">Role / Alias</th>
  544. <th class="py-2.5 px-4">MTU</th>
  545. <th class="py-2.5 px-4">Throughput</th>
  546. <th class="py-2.5 px-4">Status</th>
  547. <th class="py-2.5 px-4 text-right">Actions</th>
  548. </tr>
  549. </thead>
  550. <tbody class="divide-y divide-slate-800/70">
  551. ${childVlans.map(v => {
  552. const isVlanUp = v.state === 'UP';
  553. return `
  554. <tr class="hover:bg-slate-800/40 transition">
  555. <td class="py-2.5 px-4">
  556. <span class="px-2 py-0.5 rounded text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800 shadow-sm">
  557. VLAN ${v.vlan_id}
  558. </span>
  559. </td>
  560. <td class="py-2.5 px-4 font-bold text-white flex items-center gap-1.5">
  561. <span class="text-cyan-500">└─</span>
  562. <span>${v.name}</span>
  563. </td>
  564. <td class="py-2.5 px-4 text-emerald-400 font-medium">
  565. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  566. </td>
  567. <td class="py-2.5 px-4 font-sans text-slate-300">
  568. <span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 mr-1.5">${v.role || 'VLAN'}</span>
  569. <span class="text-slate-400 text-xs">${v.description || '-'}</span>
  570. </td>
  571. <td class="py-2.5 px-4 text-slate-400">${v.mtu}</td>
  572. <td class="py-2.5 px-4 text-[11px]">
  573. <span class="text-emerald-400">↓ ${v.rate?.rx_human || '0 B/s'}</span>
  574. <span class="text-cyan-400 ml-1.5">↑ ${v.rate?.tx_human || '0 B/s'}</span>
  575. </td>
  576. <td class="py-2.5 px-4 font-sans">
  577. <button onclick="toggleInterfaceState('${v.name}', '${isVlanUp ? 'down' : 'up'}')"
  578. class="flex items-center gap-1 text-[11px] font-semibold px-2 py-0.5 rounded-full ${
  579. 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'
  580. }">
  581. <span class="w-1.5 h-1.5 rounded-full ${isVlanUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  582. <span>${v.state}</span>
  583. </button>
  584. </td>
  585. <td class="py-2.5 px-4 text-right space-x-1.5 font-sans">
  586. <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>
  587. <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>
  588. </td>
  589. </tr>
  590. `;
  591. }).join('')}
  592. </tbody>
  593. </table>
  594. </div>
  595. `}
  596. </div>
  597. `;
  598. drawerRow.appendChild(drawerCell);
  599. tbody.appendChild(drawerRow);
  600. }
  601. });
  602. }
  603. // Render VLANs Dedicated View
  604. function renderVlansList() {
  605. const tbody = document.getElementById('vlans-table-body');
  606. const emptyState = document.getElementById('vlans-empty-state');
  607. const countBadge = document.getElementById('vlans-table-count');
  608. const query = (document.getElementById('vlan-search')?.value || '').toLowerCase();
  609. tbody.innerHTML = '';
  610. const allVlans = state.vlans || [];
  611. countBadge.innerText = allVlans.length;
  612. const filtered = allVlans.filter(v => {
  613. if (!query) return true;
  614. return v.name.toLowerCase().includes(query) ||
  615. String(v.vlan_id).includes(query) ||
  616. (v.description || '').toLowerCase().includes(query) ||
  617. (v.ipv4 && v.ipv4.some(ip => ip.includes(query)));
  618. });
  619. if (allVlans.length === 0) {
  620. emptyState.classList.remove('hidden');
  621. return;
  622. }
  623. emptyState.classList.add('hidden');
  624. filtered.forEach(v => {
  625. const isUp = v.state === 'UP';
  626. const tr = document.createElement('tr');
  627. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  628. tr.innerHTML = `
  629. <td class="py-3 px-4">
  630. <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">
  631. VLAN ${v.vlan_id}
  632. </span>
  633. </td>
  634. <td class="py-3 px-4 font-bold text-white">${v.name}</td>
  635. <td class="py-3 px-4 text-slate-300">
  636. <span class="bg-slate-800 text-slate-200 px-2 py-0.5 rounded text-[11px]">${v.parent_name || 'eth0'}</span>
  637. </td>
  638. <td class="py-3 px-4 text-emerald-400 font-medium">
  639. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  640. </td>
  641. <td class="py-3 px-4 text-slate-300 font-sans">
  642. <span class="text-slate-400 text-xs">${v.description || v.role || '-'}</span>
  643. </td>
  644. <td class="py-3 px-4 text-slate-400">${v.mtu}</td>
  645. <td class="py-3 px-4 font-sans">
  646. <button onclick="toggleInterfaceState('${v.name}', '${isUp ? 'down' : 'up'}')"
  647. class="flex items-center gap-1.5 text-xs font-semibold px-2 py-0.5 rounded-full ${
  648. 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'
  649. }">
  650. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  651. <span>${v.state}</span>
  652. </button>
  653. </td>
  654. <td class="py-3 px-4 text-right space-x-2 font-sans">
  655. <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>
  656. <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>
  657. </td>
  658. `;
  659. tbody.appendChild(tr);
  660. });
  661. }
  662. // Toggle interface UP / DOWN
  663. async function toggleInterfaceState(name, newState) {
  664. try {
  665. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(name)}/state`, {
  666. method: 'POST',
  667. headers: { 'Content-Type': 'application/json' },
  668. body: JSON.stringify({ state: newState })
  669. });
  670. const data = await res.json();
  671. if (res.ok) {
  672. showToast('Interface Updated', `Interface ${name} is now ${newState.toUpperCase()}`, 'success');
  673. fetchData(false);
  674. } else {
  675. showToast('Error', data.message || 'Failed to toggle interface state', 'error');
  676. }
  677. } catch (err) {
  678. showToast('Error', err.message, 'error');
  679. }
  680. }
  681. // ---------------- MikroTik Flag & Utilities ----------------
  682. function renderMikroTikFlag(running, disabled) {
  683. if (running) {
  684. 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>`;
  685. }
  686. if (disabled) {
  687. 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>`;
  688. }
  689. 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>`;
  690. }
  691. function copyToClipboard(text, label = 'Text') {
  692. navigator.clipboard.writeText(text).then(() => {
  693. showToast('Copied', `${label} copied to clipboard`, 'success');
  694. }).catch(() => {
  695. prompt('Copy value:', text);
  696. });
  697. }
  698. // ======================== PPPoE Multi-Instance ========================
  699. async function loadPPPoE(populateInputs = true) {
  700. try {
  701. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`);
  702. const list = await res.json();
  703. state.pppoeList = Array.isArray(list) ? list : [];
  704. const badge = document.getElementById('pppoe-count-badge');
  705. if (badge) badge.innerText = `${state.pppoeList.length} Interface${state.pppoeList.length !== 1 ? 's' : ''}`;
  706. const tbody = document.getElementById('pppoe-table-body');
  707. const empty = document.getElementById('pppoe-empty');
  708. if (!tbody) return;
  709. tbody.innerHTML = '';
  710. if (state.pppoeList.length === 0) {
  711. if (empty) empty.classList.remove('hidden');
  712. } else {
  713. if (empty) empty.classList.add('hidden');
  714. state.pppoeList.forEach(inst => {
  715. const tr = document.createElement('tr');
  716. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  717. tr.innerHTML = `
  718. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  719. <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
  720. <td class="py-2.5 px-3 text-cyan-400 font-mono">${inst.interface}</td>
  721. <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
  722. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
  723. <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
  724. <td class="py-2.5 px-3 text-center">
  725. <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'}">
  726. ${inst.default_route ? 'Yes' : 'No'}
  727. </span>
  728. </td>
  729. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  730. ${inst.running ? `
  731. <button onclick="disconnectPPPoEInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  732. ` : `
  733. <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>
  734. `}
  735. <button onclick="togglePPPoEState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  736. ${inst.disabled ? 'Enable' : 'Disable'}
  737. </button>
  738. <button onclick="openEditPPPoEModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  739. <button onclick="deletePPPoEInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  740. </td>
  741. `;
  742. tbody.appendChild(tr);
  743. });
  744. }
  745. } catch (err) {
  746. console.error('Failed to load PPPoE:', err);
  747. }
  748. }
  749. function openAddPPPoEModal() {
  750. document.getElementById('pppoe-modal-title').innerText = 'Add PPPoE Client Interface';
  751. document.getElementById('pppoe-modal-edit-orig').value = '';
  752. document.getElementById('pppoe-modal-name').value = `pppoe-out${(state.pppoeList || []).length + 1}`;
  753. document.getElementById('pppoe-modal-name').readOnly = false;
  754. document.getElementById('pppoe-modal-user').value = '';
  755. document.getElementById('pppoe-modal-pass').value = '';
  756. document.getElementById('pppoe-modal-service').value = '';
  757. document.getElementById('pppoe-modal-mtu').value = '1492';
  758. document.getElementById('pppoe-modal-defroute').checked = true;
  759. document.getElementById('pppoe-modal-reconnect').checked = true;
  760. document.getElementById('pppoe-modal-disabled').checked = false;
  761. // Populate interfaces
  762. const sel = document.getElementById('pppoe-modal-iface');
  763. sel.innerHTML = '';
  764. (state.interfaces || []).forEach(i => {
  765. if (i.name === 'lo') return;
  766. const opt = document.createElement('option');
  767. opt.value = i.name;
  768. opt.innerText = `${i.name} (${i.role || i.type})`;
  769. sel.appendChild(opt);
  770. });
  771. document.getElementById('pppoe-modal').classList.remove('hidden');
  772. }
  773. function openEditPPPoEModal(name) {
  774. const inst = (state.pppoeList || []).find(i => i.name === name);
  775. if (!inst) return;
  776. document.getElementById('pppoe-modal-title').innerText = `Edit PPPoE Client: ${name}`;
  777. document.getElementById('pppoe-modal-edit-orig').value = name;
  778. document.getElementById('pppoe-modal-name').value = inst.name;
  779. document.getElementById('pppoe-modal-name').readOnly = true;
  780. document.getElementById('pppoe-modal-user').value = inst.username || '';
  781. document.getElementById('pppoe-modal-pass').value = inst.password || '';
  782. document.getElementById('pppoe-modal-service').value = inst.service_name || '';
  783. document.getElementById('pppoe-modal-mtu').value = inst.mtu || 1492;
  784. document.getElementById('pppoe-modal-defroute').checked = inst.default_route ?? true;
  785. document.getElementById('pppoe-modal-reconnect').checked = inst.auto_reconnect ?? true;
  786. document.getElementById('pppoe-modal-disabled').checked = !!inst.disabled;
  787. const sel = document.getElementById('pppoe-modal-iface');
  788. sel.innerHTML = '';
  789. (state.interfaces || []).forEach(i => {
  790. if (i.name === 'lo') return;
  791. const opt = document.createElement('option');
  792. opt.value = i.name;
  793. opt.innerText = `${i.name} (${i.role || i.type})`;
  794. if (i.name === inst.interface) opt.selected = true;
  795. sel.appendChild(opt);
  796. });
  797. document.getElementById('pppoe-modal').classList.remove('hidden');
  798. }
  799. function closePPPoEModal() {
  800. document.getElementById('pppoe-modal').classList.add('hidden');
  801. }
  802. async function submitSavePPPoE(e) {
  803. e.preventDefault();
  804. const name = document.getElementById('pppoe-modal-name').value.trim();
  805. const iface = document.getElementById('pppoe-modal-iface').value;
  806. const user = document.getElementById('pppoe-modal-user').value.trim();
  807. const pass = document.getElementById('pppoe-modal-pass').value;
  808. const service = document.getElementById('pppoe-modal-service').value.trim();
  809. const mtu = parseInt(document.getElementById('pppoe-modal-mtu').value, 10) || 1492;
  810. const defRoute = document.getElementById('pppoe-modal-defroute').checked;
  811. const reconnect = document.getElementById('pppoe-modal-reconnect').checked;
  812. const disabled = document.getElementById('pppoe-modal-disabled').checked;
  813. try {
  814. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`, {
  815. method: 'POST',
  816. headers: { 'Content-Type': 'application/json' },
  817. body: JSON.stringify({
  818. name,
  819. interface: iface,
  820. username: user,
  821. password: pass,
  822. service_name: service,
  823. mtu,
  824. default_route: defRoute,
  825. auto_reconnect: reconnect,
  826. disabled
  827. })
  828. });
  829. if (res.ok) {
  830. showToast('PPPoE Saved', `Configuration for ${name} saved`, 'success');
  831. closePPPoEModal();
  832. loadPPPoE(false);
  833. fetchData(false);
  834. } else {
  835. const err = await res.json();
  836. showToast('Error', err.message || 'Failed to save PPPoE', 'error');
  837. }
  838. } catch (err) {
  839. showToast('Error', err.message, 'error');
  840. }
  841. }
  842. async function connectPPPoEInstance(name) {
  843. try {
  844. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  845. if (res.ok) {
  846. showToast('Connecting', `Dialing ${name}...`, 'info');
  847. setTimeout(() => loadPPPoE(false), 2000);
  848. }
  849. } catch (err) {
  850. showToast('Error', err.message, 'error');
  851. }
  852. }
  853. async function disconnectPPPoEInstance(name) {
  854. try {
  855. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  856. if (res.ok) {
  857. showToast('Disconnected', `${name} session terminated`, 'info');
  858. setTimeout(() => loadPPPoE(false), 1000);
  859. }
  860. } catch (err) {
  861. showToast('Error', err.message, 'error');
  862. }
  863. }
  864. async function togglePPPoEState(name, enable) {
  865. try {
  866. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/state`, {
  867. method: 'POST',
  868. headers: { 'Content-Type': 'application/json' },
  869. body: JSON.stringify({ enabled: enable })
  870. });
  871. if (res.ok) {
  872. showToast(enable ? 'Enabled' : 'Disabled', `${name} is now ${enable ? 'enabled' : 'disabled'}`, 'info');
  873. loadPPPoE(false);
  874. }
  875. } catch (err) {
  876. showToast('Error', err.message, 'error');
  877. }
  878. }
  879. async function deletePPPoEInstance(name) {
  880. if (!confirm(`Are you sure you want to delete PPPoE client ${name}?`)) return;
  881. try {
  882. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  883. if (res.ok) {
  884. showToast('Deleted', `PPPoE client ${name} removed`, 'success');
  885. loadPPPoE(false);
  886. fetchData(false);
  887. }
  888. } catch (err) {
  889. showToast('Error', err.message, 'error');
  890. }
  891. }
  892. // ======================== WireGuard Multi-Interface & Multi-Peer ========================
  893. state.wgSubTab = 'ifaces';
  894. function switchWGSubTab(tab) {
  895. state.wgSubTab = tab;
  896. const ifacesPanel = document.getElementById('wg-subtab-ifaces');
  897. const peersPanel = document.getElementById('wg-subtab-peers');
  898. const ifacesBtn = document.getElementById('wg-subtab-btn-ifaces');
  899. const peersBtn = document.getElementById('wg-subtab-btn-peers');
  900. if (tab === 'ifaces') {
  901. ifacesPanel?.classList.remove('hidden');
  902. peersPanel?.classList.add('hidden');
  903. 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';
  904. 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';
  905. } else {
  906. ifacesPanel?.classList.add('hidden');
  907. peersPanel?.classList.remove('hidden');
  908. 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';
  909. 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';
  910. renderWGPeers();
  911. }
  912. }
  913. async function loadWireGuard(populateInputs = true) {
  914. try {
  915. const [ifacesRes, peersRes] = await Promise.all([
  916. fetch(`${API_BASE}/vpn/wireguard/interfaces`),
  917. fetch(`${API_BASE}/vpn/wireguard/peers`)
  918. ]);
  919. const ifaces = ifacesRes.ok ? await ifacesRes.json() : [];
  920. const peers = peersRes.ok ? await peersRes.json() : [];
  921. state.wgInterfaces = Array.isArray(ifaces) ? ifaces : [];
  922. state.wgPeers = Array.isArray(peers) ? peers : [];
  923. // Badges
  924. const ifacesCountBadge = document.getElementById('wg-ifaces-count');
  925. if (ifacesCountBadge) ifacesCountBadge.innerText = `${state.wgInterfaces.length} Interfaces`;
  926. const peersCountBadge = document.getElementById('wg-peers-count');
  927. if (peersCountBadge) peersCountBadge.innerText = `${state.wgPeers.length} Peers`;
  928. const subTabIfaces = document.getElementById('wg-subtab-badge-ifaces');
  929. if (subTabIfaces) subTabIfaces.innerText = state.wgInterfaces.length;
  930. const subTabPeers = document.getElementById('wg-subtab-badge-peers');
  931. if (subTabPeers) subTabPeers.innerText = state.wgPeers.length;
  932. // Render Interfaces
  933. const ifacesTbody = document.getElementById('wg-ifaces-table-body');
  934. const ifacesEmpty = document.getElementById('wg-ifaces-empty');
  935. if (ifacesTbody) {
  936. ifacesTbody.innerHTML = '';
  937. if (state.wgInterfaces.length === 0) {
  938. if (ifacesEmpty) ifacesEmpty.classList.remove('hidden');
  939. } else {
  940. if (ifacesEmpty) ifacesEmpty.classList.add('hidden');
  941. state.wgInterfaces.forEach(iface => {
  942. const peersOnIface = state.wgPeers.filter(p => p.interface === iface.name).length;
  943. const tr = document.createElement('tr');
  944. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  945. tr.innerHTML = `
  946. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(iface.running, iface.disabled)}</td>
  947. <td class="py-2.5 px-3 font-bold text-white">${iface.name}</td>
  948. <td class="py-2.5 px-3 text-amber-400 font-mono">${iface.listen_port}</td>
  949. <td class="py-2.5 px-3 text-emerald-400 font-mono">${iface.address || '-'}</td>
  950. <td class="py-2.5 px-3 text-slate-300 font-mono">
  951. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${iface.public_key}', 'Public Key')" title="Click to copy: ${iface.public_key}">
  952. ${(iface.public_key || '').substring(0, 10)}... 📋
  953. </span>
  954. </td>
  955. <td class="py-2.5 px-3 text-slate-400 font-mono">${iface.mtu || 1420}</td>
  956. <td class="py-2.5 px-3 text-center">
  957. <span class="px-2 py-0.5 rounded text-[10px] font-sans bg-slate-800 text-slate-300">${peersOnIface} peer${peersOnIface !== 1 ? 's' : ''}</span>
  958. </td>
  959. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  960. ${iface.running ? `
  961. <button onclick="stopWGInterface('${iface.name}')" class="text-xs text-rose-400 hover:text-rose-300">Stop</button>
  962. ` : `
  963. <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>
  964. `}
  965. <button onclick="toggleWGInterfaceState('${iface.name}', ${iface.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  966. ${iface.disabled ? 'Enable' : 'Disable'}
  967. </button>
  968. <button onclick="openEditWGInterfaceModal('${iface.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  969. <button onclick="deleteWGInterface('${iface.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  970. </td>
  971. `;
  972. ifacesTbody.appendChild(tr);
  973. });
  974. }
  975. }
  976. // Populate filter dropdown in peers tab
  977. const filterSel = document.getElementById('wg-peers-filter-iface');
  978. if (filterSel) {
  979. const currentVal = filterSel.value;
  980. filterSel.innerHTML = '<option value="">All Interfaces</option>';
  981. state.wgInterfaces.forEach(i => {
  982. const opt = document.createElement('option');
  983. opt.value = i.name;
  984. opt.innerText = i.name;
  985. if (i.name === currentVal) opt.selected = true;
  986. filterSel.appendChild(opt);
  987. });
  988. }
  989. renderWGPeers();
  990. } catch (err) {
  991. console.error('Failed to load WireGuard:', err);
  992. }
  993. }
  994. function renderWGPeers() {
  995. const filterSel = document.getElementById('wg-peers-filter-iface');
  996. const selectedIface = filterSel ? filterSel.value : '';
  997. const tbody = document.getElementById('wg-peers-table-body');
  998. const empty = document.getElementById('wg-peers-empty');
  999. if (!tbody) return;
  1000. tbody.innerHTML = '';
  1001. const filtered = selectedIface ? state.wgPeers.filter(p => p.interface === selectedIface) : state.wgPeers;
  1002. if (filtered.length === 0) {
  1003. if (empty) empty.classList.remove('hidden');
  1004. } else {
  1005. if (empty) empty.classList.add('hidden');
  1006. filtered.forEach(p => {
  1007. const isOnline = p.latest_handshake && !p.latest_handshake.includes('Never');
  1008. const tr = document.createElement('tr');
  1009. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1010. tr.innerHTML = `
  1011. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isOnline, p.disabled)}</td>
  1012. <td class="py-2.5 px-3 font-mono font-bold text-rose-400">${p.interface}</td>
  1013. <td class="py-2.5 px-3 font-bold text-white font-sans">${p.name || 'Unnamed'}</td>
  1014. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1015. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${p.public_key}', 'Peer Public Key')" title="${p.public_key}">
  1016. ${p.public_key.substring(0, 10)}... 📋
  1017. </span>
  1018. </td>
  1019. <td class="py-2.5 px-3 text-emerald-400 font-mono font-semibold">${(p.allowed_ips || []).join(', ')}</td>
  1020. <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>
  1021. <td class="py-2.5 px-3 text-slate-300 font-sans">${p.latest_handshake || 'Never'}</td>
  1022. <td class="py-2.5 px-3 font-mono text-[11px]">
  1023. <span class="text-emerald-400">↓ ${p.transfer_rx_human || '0 B'}</span>
  1024. <span class="text-cyan-400 ml-1">↑ ${p.transfer_tx_human || '0 B'}</span>
  1025. </td>
  1026. <td class="py-2.5 px-3 text-right font-sans space-x-2">
  1027. <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>
  1028. <button onclick="deleteWGPeer('${p.interface}', '${p.public_key}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  1029. </td>
  1030. `;
  1031. tbody.appendChild(tr);
  1032. });
  1033. }
  1034. }
  1035. function openAddWGInterfaceModal() {
  1036. document.getElementById('wg-iface-modal-title').innerText = 'Add WireGuard Interface';
  1037. document.getElementById('wg-iface-modal-edit-orig').value = '';
  1038. document.getElementById('wg-iface-modal-name').value = `wg${(state.wgInterfaces || []).length}`;
  1039. document.getElementById('wg-iface-modal-name').readOnly = false;
  1040. document.getElementById('wg-iface-modal-port').value = 51820 + (state.wgInterfaces || []).length;
  1041. document.getElementById('wg-iface-modal-addr').value = `10.${10 + (state.wgInterfaces || []).length}.0.1/24`;
  1042. document.getElementById('wg-iface-modal-mtu').value = '1420';
  1043. document.getElementById('wg-iface-modal-pubkey').value = '';
  1044. document.getElementById('wg-iface-modal-privkey').value = '';
  1045. document.getElementById('wg-iface-modal-disabled').checked = false;
  1046. generateWGInterfaceKeys();
  1047. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1048. }
  1049. function openEditWGInterfaceModal(name) {
  1050. const iface = (state.wgInterfaces || []).find(i => i.name === name);
  1051. if (!iface) return;
  1052. document.getElementById('wg-iface-modal-title').innerText = `Edit WireGuard Interface: ${name}`;
  1053. document.getElementById('wg-iface-modal-edit-orig').value = name;
  1054. document.getElementById('wg-iface-modal-name').value = iface.name;
  1055. document.getElementById('wg-iface-modal-name').readOnly = true;
  1056. document.getElementById('wg-iface-modal-port').value = iface.listen_port || 51820;
  1057. document.getElementById('wg-iface-modal-addr').value = iface.address || '';
  1058. document.getElementById('wg-iface-modal-mtu').value = iface.mtu || 1420;
  1059. document.getElementById('wg-iface-modal-pubkey').value = iface.public_key || '';
  1060. document.getElementById('wg-iface-modal-privkey').value = iface.private_key || '';
  1061. document.getElementById('wg-iface-modal-disabled').checked = !!iface.disabled;
  1062. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1063. }
  1064. function closeAddWGInterfaceModal() {
  1065. document.getElementById('wg-iface-modal').classList.add('hidden');
  1066. }
  1067. async function generateWGInterfaceKeys() {
  1068. try {
  1069. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1070. const keys = await res.json();
  1071. if (res.ok) {
  1072. document.getElementById('wg-iface-modal-privkey').value = keys.private_key;
  1073. document.getElementById('wg-iface-modal-pubkey').value = keys.public_key;
  1074. }
  1075. } catch (err) {
  1076. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1077. }
  1078. }
  1079. async function submitSaveWGInterface(e) {
  1080. e.preventDefault();
  1081. const name = document.getElementById('wg-iface-modal-name').value.trim();
  1082. const port = parseInt(document.getElementById('wg-iface-modal-port').value, 10) || 51820;
  1083. const addr = document.getElementById('wg-iface-modal-addr').value.trim();
  1084. const mtu = parseInt(document.getElementById('wg-iface-modal-mtu').value, 10) || 1420;
  1085. const pub = document.getElementById('wg-iface-modal-pubkey').value.trim();
  1086. const priv = document.getElementById('wg-iface-modal-privkey').value.trim();
  1087. const disabled = document.getElementById('wg-iface-modal-disabled').checked;
  1088. try {
  1089. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces`, {
  1090. method: 'POST',
  1091. headers: { 'Content-Type': 'application/json' },
  1092. body: JSON.stringify({
  1093. name,
  1094. listen_port: port,
  1095. address: addr,
  1096. mtu,
  1097. public_key: pub,
  1098. private_key: priv,
  1099. disabled
  1100. })
  1101. });
  1102. if (res.ok) {
  1103. showToast('WireGuard Saved', `Interface ${name} configured`, 'success');
  1104. closeAddWGInterfaceModal();
  1105. loadWireGuard(false);
  1106. fetchData(false);
  1107. }
  1108. } catch (err) {
  1109. showToast('Error', err.message, 'error');
  1110. }
  1111. }
  1112. async function startWGInterface(name) {
  1113. try {
  1114. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1115. if (res.ok) {
  1116. showToast('Interface UP', `Started WireGuard interface ${name}`, 'success');
  1117. loadWireGuard(false);
  1118. fetchData(false);
  1119. }
  1120. } catch (err) {
  1121. showToast('Error', err.message, 'error');
  1122. }
  1123. }
  1124. async function stopWGInterface(name) {
  1125. try {
  1126. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1127. if (res.ok) {
  1128. showToast('Interface DOWN', `Stopped WireGuard interface ${name}`, 'info');
  1129. loadWireGuard(false);
  1130. fetchData(false);
  1131. }
  1132. } catch (err) {
  1133. showToast('Error', err.message, 'error');
  1134. }
  1135. }
  1136. async function toggleWGInterfaceState(name, enable) {
  1137. try {
  1138. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/state`, {
  1139. method: 'POST',
  1140. headers: { 'Content-Type': 'application/json' },
  1141. body: JSON.stringify({ enabled: enable })
  1142. });
  1143. if (res.ok) {
  1144. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1145. loadWireGuard(false);
  1146. }
  1147. } catch (err) {
  1148. showToast('Error', err.message, 'error');
  1149. }
  1150. }
  1151. async function deleteWGInterface(name) {
  1152. if (!confirm(`Are you sure you want to delete WireGuard interface ${name}?`)) return;
  1153. try {
  1154. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1155. if (res.ok) {
  1156. showToast('Deleted', `Interface ${name} removed`, 'success');
  1157. loadWireGuard(false);
  1158. fetchData(false);
  1159. }
  1160. } catch (err) {
  1161. showToast('Error', err.message, 'error');
  1162. }
  1163. }
  1164. function openAddWGPeerModal() {
  1165. const sel = document.getElementById('wg-peer-modal-iface');
  1166. sel.innerHTML = '';
  1167. (state.wgInterfaces || []).forEach(i => {
  1168. const opt = document.createElement('option');
  1169. opt.value = i.name;
  1170. opt.innerText = `${i.name} (${i.address || 'No IP'})`;
  1171. sel.appendChild(opt);
  1172. });
  1173. if ((state.wgInterfaces || []).length === 0) {
  1174. showToast('No Interfaces', 'Please add a WireGuard interface first before adding peers', 'warning');
  1175. openAddWGInterfaceModal();
  1176. return;
  1177. }
  1178. document.getElementById('wg-peer-modal-name').value = '';
  1179. document.getElementById('wg-peer-modal-pubkey').value = '';
  1180. document.getElementById('wg-peer-modal-allowedips').value = '10.10.0.2/32';
  1181. document.getElementById('wg-peer-modal-endpoint').value = '';
  1182. document.getElementById('wg-peer-modal-keepalive').value = '25';
  1183. document.getElementById('wg-peer-modal-preshared').value = '';
  1184. document.getElementById('wg-peer-modal-disabled').checked = false;
  1185. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1186. }
  1187. function closeAddWGPeerModal() {
  1188. document.getElementById('wg-peer-modal').classList.add('hidden');
  1189. }
  1190. async function submitSaveWGPeer(e) {
  1191. e.preventDefault();
  1192. const iface = document.getElementById('wg-peer-modal-iface').value;
  1193. const name = document.getElementById('wg-peer-modal-name').value.trim();
  1194. const pub = document.getElementById('wg-peer-modal-pubkey').value.trim();
  1195. const allowed = document.getElementById('wg-peer-modal-allowedips').value.split(',').map(s => s.trim());
  1196. const ep = document.getElementById('wg-peer-modal-endpoint').value.trim();
  1197. const keepalive = parseInt(document.getElementById('wg-peer-modal-keepalive').value, 10) || 25;
  1198. const psk = document.getElementById('wg-peer-modal-preshared').value.trim();
  1199. const disabled = document.getElementById('wg-peer-modal-disabled').checked;
  1200. let epAddr = ep;
  1201. let epPort = 0;
  1202. if (ep.includes(':')) {
  1203. const parts = ep.split(':');
  1204. epAddr = parts[0];
  1205. epPort = parseInt(parts[1], 10) || 0;
  1206. }
  1207. try {
  1208. const res = await fetch(`${API_BASE}/vpn/wireguard/peers`, {
  1209. method: 'POST',
  1210. headers: { 'Content-Type': 'application/json' },
  1211. body: JSON.stringify({
  1212. interface: iface,
  1213. name,
  1214. public_key: pub,
  1215. allowed_ips: allowed,
  1216. endpoint_address: epAddr,
  1217. endpoint_port: epPort,
  1218. persistent_keepalive: keepalive,
  1219. preshared_key: psk,
  1220. disabled
  1221. })
  1222. });
  1223. if (res.ok) {
  1224. showToast('Peer Saved', `Peer ${name} added to ${iface}`, 'success');
  1225. closeAddWGPeerModal();
  1226. loadWireGuard(false);
  1227. }
  1228. } catch (err) {
  1229. showToast('Error', err.message, 'error');
  1230. }
  1231. }
  1232. async function deleteWGPeer(iface, pubkey) {
  1233. if (!confirm(`Are you sure you want to remove peer from ${iface}?`)) return;
  1234. try {
  1235. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/${encodeURIComponent(iface)}/${encodeURIComponent(pubkey)}`, {
  1236. method: 'DELETE'
  1237. });
  1238. if (res.ok) {
  1239. showToast('Peer Deleted', 'WireGuard peer removed', 'success');
  1240. loadWireGuard(false);
  1241. }
  1242. } catch (err) {
  1243. showToast('Error', err.message, 'error');
  1244. }
  1245. }
  1246. // ======================== IPSec Multi-Tunnel ========================
  1247. async function loadIPSec(populateInputs = true) {
  1248. try {
  1249. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`);
  1250. const list = await res.json();
  1251. state.ipsecTunnels = Array.isArray(list) ? list : [];
  1252. const activeCount = state.ipsecTunnels.filter(t => t.running || t.status === 'ESTABLISHED').length;
  1253. const badge = document.getElementById('ipsec-sas-badge');
  1254. if (badge) badge.innerText = `${activeCount} Active SAs`;
  1255. const tbody = document.getElementById('ipsec-table-body');
  1256. const empty = document.getElementById('ipsec-empty');
  1257. if (!tbody) return;
  1258. tbody.innerHTML = '';
  1259. if (state.ipsecTunnels.length === 0) {
  1260. if (empty) empty.classList.remove('hidden');
  1261. } else {
  1262. if (empty) empty.classList.add('hidden');
  1263. state.ipsecTunnels.forEach(c => {
  1264. const isEstablished = c.running || c.status === 'ESTABLISHED';
  1265. const tr = document.createElement('tr');
  1266. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1267. tr.innerHTML = `
  1268. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isEstablished, c.disabled)}</td>
  1269. <td class="py-2.5 px-4 font-bold text-white">${c.name}</td>
  1270. <td class="py-2.5 px-4 text-emerald-400 font-mono">${c.local_subnet || '-'}</td>
  1271. <td class="py-2.5 px-4 text-slate-300 font-mono">${c.remote_addrs || '-'}</td>
  1272. <td class="py-2.5 px-4 text-cyan-400 font-mono">${c.remote_subnet || '-'}</td>
  1273. <td class="py-2.5 px-4 font-sans">
  1274. <span class="px-2 py-0.5 rounded-full text-[10px] font-semibold ${
  1275. isEstablished ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30' : 'bg-slate-800 text-slate-400'
  1276. }">${c.status || (isEstablished ? 'ESTABLISHED' : 'DISCONNECTED')}</span>
  1277. </td>
  1278. <td class="py-2.5 px-4 text-right space-x-2 font-sans">
  1279. ${isEstablished ? `
  1280. <button onclick="stopIPSecTunnel('${c.name}')" class="text-xs text-rose-400 hover:text-rose-300">Terminate</button>
  1281. ` : `
  1282. <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>
  1283. `}
  1284. <button onclick="toggleIPSecState('${c.name}', ${c.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1285. ${c.disabled ? 'Enable' : 'Disable'}
  1286. </button>
  1287. <button onclick="openEditIPSecModal('${c.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1288. <button onclick="deleteIPSecConn('${c.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1289. </td>
  1290. `;
  1291. tbody.appendChild(tr);
  1292. });
  1293. }
  1294. } catch (err) {
  1295. console.error('Failed to load IPSec:', err);
  1296. }
  1297. }
  1298. function openAddIPSecModal() {
  1299. document.getElementById('ipsec-modal-title').innerText = 'Configure IPSec IKEv2 Tunnel';
  1300. document.getElementById('ipsec-modal-name').value = `ipsec-${(state.ipsecTunnels || []).length + 1}`;
  1301. document.getElementById('ipsec-modal-name').readOnly = false;
  1302. document.getElementById('ipsec-modal-localts').value = '192.168.10.0/24';
  1303. document.getElementById('ipsec-modal-remotets').value = '192.168.20.0/24';
  1304. document.getElementById('ipsec-modal-remotegw').value = '';
  1305. document.getElementById('ipsec-modal-psk').value = '';
  1306. document.getElementById('ipsec-modal-ikeprop').value = 'aes256-sha256-modp2048,default';
  1307. document.getElementById('ipsec-modal-espprop').value = 'aes256-sha256-modp2048,default';
  1308. document.getElementById('ipsec-modal-autostart').checked = true;
  1309. document.getElementById('ipsec-modal-disabled').checked = false;
  1310. document.getElementById('ipsec-modal').classList.remove('hidden');
  1311. }
  1312. function openEditIPSecModal(name) {
  1313. const conn = (state.ipsecTunnels || []).find(c => c.name === name);
  1314. if (!conn) return;
  1315. document.getElementById('ipsec-modal-title').innerText = `Edit IPSec Tunnel: ${name}`;
  1316. document.getElementById('ipsec-modal-name').value = conn.name;
  1317. document.getElementById('ipsec-modal-name').readOnly = true;
  1318. document.getElementById('ipsec-modal-localts').value = conn.local_subnet || '';
  1319. document.getElementById('ipsec-modal-remotets').value = conn.remote_subnet || '';
  1320. document.getElementById('ipsec-modal-remotegw').value = conn.remote_addrs || '';
  1321. document.getElementById('ipsec-modal-psk').value = conn.preshared_key || '';
  1322. document.getElementById('ipsec-modal-ikeprop').value = conn.ike_proposals || 'aes256-sha256-modp2048,default';
  1323. document.getElementById('ipsec-modal-espprop').value = conn.esp_proposals || 'aes256-sha256-modp2048,default';
  1324. document.getElementById('ipsec-modal-autostart').checked = conn.auto_start ?? true;
  1325. document.getElementById('ipsec-modal-disabled').checked = !!conn.disabled;
  1326. document.getElementById('ipsec-modal').classList.remove('hidden');
  1327. }
  1328. function closeAddIPSecModal() {
  1329. document.getElementById('ipsec-modal').classList.add('hidden');
  1330. }
  1331. async function submitSaveIPSec(e) {
  1332. e.preventDefault();
  1333. const name = document.getElementById('ipsec-modal-name').value.trim();
  1334. const localts = document.getElementById('ipsec-modal-localts').value.trim();
  1335. const remotets = document.getElementById('ipsec-modal-remotets').value.trim();
  1336. const remotegw = document.getElementById('ipsec-modal-remotegw').value.trim();
  1337. const psk = document.getElementById('ipsec-modal-psk').value;
  1338. const ike = document.getElementById('ipsec-modal-ikeprop').value.trim();
  1339. const esp = document.getElementById('ipsec-modal-espprop').value.trim();
  1340. const autostart = document.getElementById('ipsec-modal-autostart').checked;
  1341. const disabled = document.getElementById('ipsec-modal-disabled').checked;
  1342. try {
  1343. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`, {
  1344. method: 'POST',
  1345. headers: { 'Content-Type': 'application/json' },
  1346. body: JSON.stringify({
  1347. name,
  1348. local_addrs: '%any',
  1349. remote_addrs: remotegw,
  1350. local_subnet: localts,
  1351. remote_subnet: remotets,
  1352. preshared_key: psk,
  1353. ike_proposals: ike,
  1354. esp_proposals: esp,
  1355. auto_start: autostart,
  1356. disabled
  1357. })
  1358. });
  1359. if (res.ok) {
  1360. showToast('IPSec Saved', `Tunnel ${name} configured`, 'success');
  1361. closeAddIPSecModal();
  1362. loadIPSec(false);
  1363. fetchData(false);
  1364. }
  1365. } catch (err) {
  1366. showToast('Error', err.message, 'error');
  1367. }
  1368. }
  1369. async function startIPSecTunnel(name) {
  1370. try {
  1371. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1372. if (res.ok) {
  1373. showToast('Initiating Tunnel', `Attempting SA handshake for ${name}...`, 'info');
  1374. setTimeout(() => loadIPSec(false), 2000);
  1375. }
  1376. } catch (err) {
  1377. showToast('Error', err.message, 'error');
  1378. }
  1379. }
  1380. async function stopIPSecTunnel(name) {
  1381. try {
  1382. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1383. if (res.ok) {
  1384. showToast('Terminated', `IPSec SA for ${name} closed`, 'info');
  1385. loadIPSec(false);
  1386. }
  1387. } catch (err) {
  1388. showToast('Error', err.message, 'error');
  1389. }
  1390. }
  1391. async function toggleIPSecState(name, enable) {
  1392. try {
  1393. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/state`, {
  1394. method: 'POST',
  1395. headers: { 'Content-Type': 'application/json' },
  1396. body: JSON.stringify({ enabled: enable })
  1397. });
  1398. if (res.ok) {
  1399. showToast(enable ? 'Enabled' : 'Disabled', `IPSec tunnel ${name} updated`, 'info');
  1400. loadIPSec(false);
  1401. }
  1402. } catch (err) {
  1403. showToast('Error', err.message, 'error');
  1404. }
  1405. }
  1406. async function deleteIPSecConn(name) {
  1407. if (!confirm(`Are you sure you want to delete IPSec tunnel ${name}?`)) return;
  1408. try {
  1409. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1410. if (res.ok) {
  1411. showToast('Deleted', `IPSec connection ${name} removed`, 'success');
  1412. loadIPSec(false);
  1413. fetchData(false);
  1414. }
  1415. } catch (err) {
  1416. showToast('Error', err.message, 'error');
  1417. }
  1418. }
  1419. // ======================== L2TP Multi-Instance ========================
  1420. async function loadL2TP(populateInputs = true) {
  1421. try {
  1422. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`);
  1423. const list = await res.json();
  1424. state.l2tpList = Array.isArray(list) ? list : [];
  1425. const badge = document.getElementById('l2tp-count-badge');
  1426. if (badge) badge.innerText = `${state.l2tpList.length} Client${state.l2tpList.length !== 1 ? 's' : ''}`;
  1427. const tbody = document.getElementById('l2tp-table-body');
  1428. const empty = document.getElementById('l2tp-empty');
  1429. if (!tbody) return;
  1430. tbody.innerHTML = '';
  1431. if (state.l2tpList.length === 0) {
  1432. if (empty) empty.classList.remove('hidden');
  1433. } else {
  1434. if (empty) empty.classList.add('hidden');
  1435. state.l2tpList.forEach(inst => {
  1436. const tr = document.createElement('tr');
  1437. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1438. tr.innerHTML = `
  1439. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1440. <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
  1441. <td class="py-2.5 px-3 text-cyan-400 font-mono">${inst.connect_to}</td>
  1442. <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
  1443. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
  1444. <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
  1445. <td class="py-2.5 px-3 text-center">
  1446. <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'}">
  1447. ${inst.default_route ? 'Yes' : 'No'}
  1448. </span>
  1449. </td>
  1450. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1451. ${inst.running ? `
  1452. <button onclick="disconnectL2TPInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1453. ` : `
  1454. <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>
  1455. `}
  1456. <button onclick="toggleL2TPState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1457. ${inst.disabled ? 'Enable' : 'Disable'}
  1458. </button>
  1459. <button onclick="openEditL2TPModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1460. <button onclick="deleteL2TPInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1461. </td>
  1462. `;
  1463. tbody.appendChild(tr);
  1464. });
  1465. }
  1466. } catch (err) {
  1467. console.error('Failed to load L2TP:', err);
  1468. }
  1469. }
  1470. function openAddL2TPModal() {
  1471. document.getElementById('l2tp-modal-title').innerText = 'Add L2TP Client Interface';
  1472. document.getElementById('l2tp-modal-name').value = `l2tp-out${(state.l2tpList || []).length + 1}`;
  1473. document.getElementById('l2tp-modal-name').readOnly = false;
  1474. document.getElementById('l2tp-modal-server').value = '';
  1475. document.getElementById('l2tp-modal-user').value = '';
  1476. document.getElementById('l2tp-modal-pass').value = '';
  1477. document.getElementById('l2tp-modal-ipsec').value = '';
  1478. document.getElementById('l2tp-modal-defroute').checked = true;
  1479. document.getElementById('l2tp-modal-disabled').checked = false;
  1480. document.getElementById('l2tp-modal').classList.remove('hidden');
  1481. }
  1482. function openEditL2TPModal(name) {
  1483. const inst = (state.l2tpList || []).find(i => i.name === name);
  1484. if (!inst) return;
  1485. document.getElementById('l2tp-modal-title').innerText = `Edit L2TP Client: ${name}`;
  1486. document.getElementById('l2tp-modal-name').value = inst.name;
  1487. document.getElementById('l2tp-modal-name').readOnly = true;
  1488. document.getElementById('l2tp-modal-server').value = inst.connect_to || '';
  1489. document.getElementById('l2tp-modal-user').value = inst.username || '';
  1490. document.getElementById('l2tp-modal-pass').value = inst.password || '';
  1491. document.getElementById('l2tp-modal-ipsec').value = inst.ipsec_secret || '';
  1492. document.getElementById('l2tp-modal-defroute').checked = inst.default_route ?? true;
  1493. document.getElementById('l2tp-modal-disabled').checked = !!inst.disabled;
  1494. document.getElementById('l2tp-modal').classList.remove('hidden');
  1495. }
  1496. function closeL2TPModal() {
  1497. document.getElementById('l2tp-modal').classList.add('hidden');
  1498. }
  1499. async function submitSaveL2TP(e) {
  1500. e.preventDefault();
  1501. const name = document.getElementById('l2tp-modal-name').value.trim();
  1502. const server = document.getElementById('l2tp-modal-server').value.trim();
  1503. const user = document.getElementById('l2tp-modal-user').value.trim();
  1504. const pass = document.getElementById('l2tp-modal-pass').value;
  1505. const ipsec = document.getElementById('l2tp-modal-ipsec').value;
  1506. const defRoute = document.getElementById('l2tp-modal-defroute').checked;
  1507. const disabled = document.getElementById('l2tp-modal-disabled').checked;
  1508. try {
  1509. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`, {
  1510. method: 'POST',
  1511. headers: { 'Content-Type': 'application/json' },
  1512. body: JSON.stringify({
  1513. name,
  1514. connect_to: server,
  1515. username: user,
  1516. password: pass,
  1517. ipsec_secret: ipsec,
  1518. default_route: defRoute,
  1519. disabled
  1520. })
  1521. });
  1522. if (res.ok) {
  1523. showToast('L2TP Saved', `Client ${name} configuration saved`, 'success');
  1524. closeL2TPModal();
  1525. loadL2TP(false);
  1526. fetchData(false);
  1527. }
  1528. } catch (err) {
  1529. showToast('Error', err.message, 'error');
  1530. }
  1531. }
  1532. async function connectL2TPInstance(name) {
  1533. try {
  1534. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1535. if (res.ok) {
  1536. showToast('Connecting', `Dialing L2TP ${name}...`, 'info');
  1537. setTimeout(() => loadL2TP(false), 2000);
  1538. }
  1539. } catch (err) {
  1540. showToast('Error', err.message, 'error');
  1541. }
  1542. }
  1543. async function disconnectL2TPInstance(name) {
  1544. try {
  1545. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1546. if (res.ok) {
  1547. showToast('Disconnected', `L2TP tunnel ${name} terminated`, 'info');
  1548. loadL2TP(false);
  1549. }
  1550. } catch (err) {
  1551. showToast('Error', err.message, 'error');
  1552. }
  1553. }
  1554. async function toggleL2TPState(name, enable) {
  1555. try {
  1556. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/state`, {
  1557. method: 'POST',
  1558. headers: { 'Content-Type': 'application/json' },
  1559. body: JSON.stringify({ enabled: enable })
  1560. });
  1561. if (res.ok) {
  1562. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1563. loadL2TP(false);
  1564. }
  1565. } catch (err) {
  1566. showToast('Error', err.message, 'error');
  1567. }
  1568. }
  1569. async function deleteL2TPInstance(name) {
  1570. if (!confirm(`Are you sure you want to delete L2TP client ${name}?`)) return;
  1571. try {
  1572. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1573. if (res.ok) {
  1574. showToast('Deleted', `L2TP client ${name} removed`, 'success');
  1575. loadL2TP(false);
  1576. fetchData(false);
  1577. }
  1578. } catch (err) {
  1579. showToast('Error', err.message, 'error');
  1580. }
  1581. }
  1582. // ======================== PPTP Multi-Instance ========================
  1583. async function loadPPTP(populateInputs = true) {
  1584. try {
  1585. const res = await fetch(`${API_BASE}/vpn/pptp/clients`);
  1586. const list = await res.json();
  1587. state.pptpList = Array.isArray(list) ? list : [];
  1588. const badge = document.getElementById('pptp-count-badge');
  1589. if (badge) badge.innerText = `${state.pptpList.length} Client${state.pptpList.length !== 1 ? 's' : ''}`;
  1590. const tbody = document.getElementById('pptp-table-body');
  1591. const empty = document.getElementById('pptp-empty');
  1592. if (!tbody) return;
  1593. tbody.innerHTML = '';
  1594. if (state.pptpList.length === 0) {
  1595. if (empty) empty.classList.remove('hidden');
  1596. } else {
  1597. if (empty) empty.classList.add('hidden');
  1598. state.pptpList.forEach(inst => {
  1599. const tr = document.createElement('tr');
  1600. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1601. tr.innerHTML = `
  1602. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1603. <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
  1604. <td class="py-2.5 px-3 text-purple-400 font-mono">${inst.connect_to}</td>
  1605. <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
  1606. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
  1607. <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
  1608. <td class="py-2.5 px-3 text-center">
  1609. <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'}">
  1610. ${inst.require_mppe ? 'MPPE-128' : 'None'}
  1611. </span>
  1612. </td>
  1613. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1614. ${inst.running ? `
  1615. <button onclick="disconnectPPTPInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1616. ` : `
  1617. <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>
  1618. `}
  1619. <button onclick="togglePPTPState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1620. ${inst.disabled ? 'Enable' : 'Disable'}
  1621. </button>
  1622. <button onclick="openEditPPTPModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1623. <button onclick="deletePPTPInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1624. </td>
  1625. `;
  1626. tbody.appendChild(tr);
  1627. });
  1628. }
  1629. } catch (err) {
  1630. console.error('Failed to load PPTP:', err);
  1631. }
  1632. }
  1633. function openAddPPTPModal() {
  1634. document.getElementById('pptp-modal-title').innerText = 'Add PPTP Client Interface';
  1635. document.getElementById('pptp-modal-name').value = `pptp-out${(state.pptpList || []).length + 1}`;
  1636. document.getElementById('pptp-modal-name').readOnly = false;
  1637. document.getElementById('pptp-modal-server').value = '';
  1638. document.getElementById('pptp-modal-user').value = '';
  1639. document.getElementById('pptp-modal-pass').value = '';
  1640. document.getElementById('pptp-modal-mppe').checked = true;
  1641. document.getElementById('pptp-modal-defroute').checked = true;
  1642. document.getElementById('pptp-modal-disabled').checked = false;
  1643. document.getElementById('pptp-modal').classList.remove('hidden');
  1644. }
  1645. function openEditPPTPModal(name) {
  1646. const inst = (state.pptpList || []).find(i => i.name === name);
  1647. if (!inst) return;
  1648. document.getElementById('pptp-modal-title').innerText = `Edit PPTP Client: ${name}`;
  1649. document.getElementById('pptp-modal-name').value = inst.name;
  1650. document.getElementById('pptp-modal-name').readOnly = true;
  1651. document.getElementById('pptp-modal-server').value = inst.connect_to || '';
  1652. document.getElementById('pptp-modal-user').value = inst.username || '';
  1653. document.getElementById('pptp-modal-pass').value = inst.password || '';
  1654. document.getElementById('pptp-modal-mppe').checked = inst.require_mppe ?? true;
  1655. document.getElementById('pptp-modal-defroute').checked = inst.default_route ?? true;
  1656. document.getElementById('pptp-modal-disabled').checked = !!inst.disabled;
  1657. document.getElementById('pptp-modal').classList.remove('hidden');
  1658. }
  1659. function closePPTPModal() {
  1660. document.getElementById('pptp-modal').classList.add('hidden');
  1661. }
  1662. async function submitSavePPTP(e) {
  1663. e.preventDefault();
  1664. const name = document.getElementById('pptp-modal-name').value.trim();
  1665. const server = document.getElementById('pptp-modal-server').value.trim();
  1666. const user = document.getElementById('pptp-modal-user').value.trim();
  1667. const pass = document.getElementById('pptp-modal-pass').value;
  1668. const mppe = document.getElementById('pptp-modal-mppe').checked;
  1669. const defRoute = document.getElementById('pptp-modal-defroute').checked;
  1670. const disabled = document.getElementById('pptp-modal-disabled').checked;
  1671. try {
  1672. const res = await fetch(`${API_BASE}/vpn/pptp/clients`, {
  1673. method: 'POST',
  1674. headers: { 'Content-Type': 'application/json' },
  1675. body: JSON.stringify({
  1676. name,
  1677. connect_to: server,
  1678. username: user,
  1679. password: pass,
  1680. require_mppe: mppe,
  1681. default_route: defRoute,
  1682. auto_reconnect: true,
  1683. disabled
  1684. })
  1685. });
  1686. if (res.ok) {
  1687. showToast('PPTP Saved', `Client ${name} configuration saved`, 'success');
  1688. closePPTPModal();
  1689. loadPPTP(false);
  1690. fetchData(false);
  1691. }
  1692. } catch (err) {
  1693. showToast('Error', err.message, 'error');
  1694. }
  1695. }
  1696. async function connectPPTPInstance(name) {
  1697. try {
  1698. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1699. if (res.ok) {
  1700. showToast('Connecting', `Dialing PPTP ${name}...`, 'info');
  1701. setTimeout(() => loadPPTP(false), 2000);
  1702. }
  1703. } catch (err) {
  1704. showToast('Error', err.message, 'error');
  1705. }
  1706. }
  1707. async function disconnectPPTPInstance(name) {
  1708. try {
  1709. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1710. if (res.ok) {
  1711. showToast('Disconnected', `PPTP tunnel ${name} terminated`, 'info');
  1712. loadPPTP(false);
  1713. }
  1714. } catch (err) {
  1715. showToast('Error', err.message, 'error');
  1716. }
  1717. }
  1718. async function togglePPTPState(name, enable) {
  1719. try {
  1720. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/state`, {
  1721. method: 'POST',
  1722. headers: { 'Content-Type': 'application/json' },
  1723. body: JSON.stringify({ enabled: enable })
  1724. });
  1725. if (res.ok) {
  1726. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1727. loadPPTP(false);
  1728. }
  1729. } catch (err) {
  1730. showToast('Error', err.message, 'error');
  1731. }
  1732. }
  1733. async function deletePPTPInstance(name) {
  1734. if (!confirm(`Are you sure you want to delete PPTP client ${name}?`)) return;
  1735. try {
  1736. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1737. if (res.ok) {
  1738. showToast('Deleted', `PPTP client ${name} removed`, 'success');
  1739. loadPPTP(false);
  1740. fetchData(false);
  1741. }
  1742. } catch (err) {
  1743. showToast('Error', err.message, 'error');
  1744. }
  1745. }
  1746. // ---------------- Modal & Helper Functions ----------------
  1747. function openVlanModal(defaultParent = '') {
  1748. const select = document.getElementById('vlan-parent');
  1749. select.innerHTML = '';
  1750. const allIfaces = state.interfaces || [];
  1751. const eligible = allIfaces.filter(i => !i.is_vlan && i.name !== 'lo');
  1752. if (eligible.length === 0) {
  1753. allIfaces.forEach(i => eligible.push(i));
  1754. }
  1755. eligible.forEach(i => {
  1756. const opt = document.createElement('option');
  1757. opt.value = i.name;
  1758. opt.innerText = `${i.name} (${i.role || 'Interface'} - ${i.state})`;
  1759. if (i.name === defaultParent) opt.selected = true;
  1760. select.appendChild(opt);
  1761. });
  1762. document.getElementById('vlan-id').value = '';
  1763. document.getElementById('vlan-name').value = '';
  1764. document.getElementById('vlan-ip').value = '';
  1765. document.getElementById('vlan-desc').value = '';
  1766. autoSuggestVlanName();
  1767. document.getElementById('vlan-modal').classList.remove('hidden');
  1768. }
  1769. function closeVlanModal() {
  1770. document.getElementById('vlan-modal').classList.add('hidden');
  1771. }
  1772. function autoSuggestVlanName() {
  1773. const parent = document.getElementById('vlan-parent').value;
  1774. const id = document.getElementById('vlan-id').value;
  1775. const nameInput = document.getElementById('vlan-name');
  1776. if (parent && id) nameInput.placeholder = `${parent}.${id}`;
  1777. }
  1778. function setSubnetPreset(cidr) {
  1779. const ipInput = document.getElementById('vlan-ip');
  1780. const id = document.getElementById('vlan-id').value || '10';
  1781. ipInput.value = `192.168.${id}.1${cidr}`;
  1782. }
  1783. async function submitCreateVlan(e) {
  1784. e.preventDefault();
  1785. const btn = document.getElementById('vlan-submit-btn');
  1786. btn.disabled = true;
  1787. btn.innerText = 'Creating...';
  1788. const parent = document.getElementById('vlan-parent').value;
  1789. const id = parseInt(document.getElementById('vlan-id').value, 10);
  1790. const name = document.getElementById('vlan-name').value.trim();
  1791. const ip = document.getElementById('vlan-ip').value.trim();
  1792. const role = document.getElementById('vlan-role').value;
  1793. const desc = document.getElementById('vlan-desc').value.trim();
  1794. try {
  1795. const res = await fetch(`${API_BASE}/vlans`, {
  1796. method: 'POST',
  1797. headers: { 'Content-Type': 'application/json' },
  1798. body: JSON.stringify({
  1799. parent_name: parent,
  1800. vlan_id: id,
  1801. name: name,
  1802. ip_address: ip,
  1803. role: role,
  1804. description: desc,
  1805. mtu: 1500,
  1806. auto_up: true
  1807. })
  1808. });
  1809. const data = await res.json();
  1810. if (res.ok) {
  1811. showToast('VLAN Created', `Created ${data.name} (VLAN ${data.vlan_id})`, 'success');
  1812. state.expandedParents.add(parent);
  1813. closeVlanModal();
  1814. await fetchData(true);
  1815. if (state.activeTab !== 'interfaces') navigate('interfaces');
  1816. } else {
  1817. showToast('Creation Failed', data.message || 'Failed to create VLAN', 'error');
  1818. }
  1819. } catch (err) {
  1820. showToast('Error', err.message, 'error');
  1821. } finally {
  1822. btn.disabled = false;
  1823. btn.innerText = 'Create VLAN';
  1824. }
  1825. }
  1826. async function confirmDeleteVlan(name) {
  1827. if (!confirm(`Delete VLAN interface ${name}?`)) return;
  1828. try {
  1829. const res = await fetch(`${API_BASE}/vlans/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1830. if (res.ok) {
  1831. showToast('VLAN Deleted', `Interface ${name} removed`, 'success');
  1832. closeIfaceModal();
  1833. fetchData(true);
  1834. }
  1835. } catch (err) {
  1836. showToast('Error', err.message, 'error');
  1837. }
  1838. }
  1839. function openIfaceModal(name) {
  1840. const iface = (state.interfaces || []).find(i => i.name === name);
  1841. if (!iface) return;
  1842. state.currentModalIface = iface.name;
  1843. document.getElementById('modal-iface-name').innerText = iface.name;
  1844. document.getElementById('modal-iface-badge').innerText = iface.is_vlan ? `VLAN ${iface.vlan_id}` : iface.type;
  1845. document.getElementById('modal-iface-mtu').value = iface.mtu;
  1846. document.getElementById('modal-iface-role').value = iface.role || 'LAN';
  1847. document.getElementById('modal-iface-desc').value = iface.description || '';
  1848. const delBtn = document.getElementById('modal-delete-vlan-btn');
  1849. if (iface.is_vlan) {
  1850. delBtn.classList.remove('hidden');
  1851. } else {
  1852. delBtn.classList.add('hidden');
  1853. }
  1854. renderModalIPs(iface);
  1855. document.getElementById('iface-modal').classList.remove('hidden');
  1856. }
  1857. function renderModalIPs(iface) {
  1858. const container = document.getElementById('modal-ip-list');
  1859. container.innerHTML = '';
  1860. const addrs = [...(iface.ipv4 || []), ...(iface.ipv6 || [])];
  1861. if (addrs.length === 0) {
  1862. container.innerHTML = `<span class="text-slate-500 text-xs font-sans">No IP addresses currently bound</span>`;
  1863. return;
  1864. }
  1865. addrs.forEach(addr => {
  1866. const row = document.createElement('div');
  1867. row.className = 'flex items-center justify-between p-2 rounded bg-slate-900 border border-slate-800';
  1868. row.innerHTML = `
  1869. <span class="text-white">${addr}</span>
  1870. <button onclick="removeInterfaceIP('${addr}')" class="text-[11px] text-rose-400 hover:text-rose-300 font-sans">Remove</button>
  1871. `;
  1872. container.appendChild(row);
  1873. });
  1874. }
  1875. function closeIfaceModal() {
  1876. document.getElementById('iface-modal').classList.add('hidden');
  1877. state.currentModalIface = null;
  1878. }
  1879. async function setIfaceState(name, newState) {
  1880. await toggleInterfaceState(name, newState);
  1881. const updated = (state.interfaces || []).find(i => i.name === name);
  1882. if (updated) openIfaceModal(name);
  1883. }
  1884. async function applyMTU() {
  1885. const mtu = parseInt(document.getElementById('modal-iface-mtu').value, 10);
  1886. try {
  1887. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/mtu`, {
  1888. method: 'POST',
  1889. headers: { 'Content-Type': 'application/json' },
  1890. body: JSON.stringify({ mtu })
  1891. });
  1892. if (res.ok) {
  1893. showToast('MTU Applied', `Set MTU to ${mtu} on ${state.currentModalIface}`, 'success');
  1894. fetchData(false);
  1895. }
  1896. } catch (err) {
  1897. showToast('Error', err.message, 'error');
  1898. }
  1899. }
  1900. async function addInterfaceIP() {
  1901. const ip = document.getElementById('modal-new-ip').value.trim();
  1902. if (!ip) return;
  1903. try {
  1904. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  1905. method: 'POST',
  1906. headers: { 'Content-Type': 'application/json' },
  1907. body: JSON.stringify({ ip })
  1908. });
  1909. if (res.ok) {
  1910. showToast('IP Added', `Bound ${ip} to ${state.currentModalIface}`, 'success');
  1911. document.getElementById('modal-new-ip').value = '';
  1912. await fetchData(false);
  1913. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  1914. if (iface) renderModalIPs(iface);
  1915. } else {
  1916. const err = await res.json();
  1917. showToast('Error', err.error || err.message || 'Failed to add IP address', 'error');
  1918. }
  1919. } catch (err) {
  1920. showToast('Error', err.message, 'error');
  1921. }
  1922. }
  1923. async function removeInterfaceIP(ip) {
  1924. if (!confirm(`Remove IP ${ip}?`)) return;
  1925. try {
  1926. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  1927. method: 'DELETE',
  1928. headers: { 'Content-Type': 'application/json' },
  1929. body: JSON.stringify({ ip })
  1930. });
  1931. if (res.ok) {
  1932. showToast('IP Removed', `Removed ${ip}`, 'success');
  1933. await fetchData(false);
  1934. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  1935. if (iface) renderModalIPs(iface);
  1936. }
  1937. } catch (err) {
  1938. showToast('Error', err.message, 'error');
  1939. }
  1940. }
  1941. async function saveInterfaceMetadata() {
  1942. const role = document.getElementById('modal-iface-role').value;
  1943. const desc = document.getElementById('modal-iface-desc').value.trim();
  1944. try {
  1945. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/metadata`, {
  1946. method: 'POST',
  1947. headers: { 'Content-Type': 'application/json' },
  1948. body: JSON.stringify({ role, description: desc })
  1949. });
  1950. if (res.ok) {
  1951. showToast('Saved', 'Metadata updated', 'success');
  1952. closeIfaceModal();
  1953. fetchData(false);
  1954. }
  1955. } catch (err) {
  1956. showToast('Error', err.message, 'error');
  1957. }
  1958. }
  1959. // ======================== MIKROTIK FIREWALL (/ip firewall) ========================
  1960. state.fwSubTab = 'filter';
  1961. state.routesSubTab = 'routes';
  1962. function renderRuleFlag(disabled, hasComment) {
  1963. let flags = '';
  1964. if (disabled) flags += '<span class="text-rose-400 font-bold" title="Disabled">X</span>';
  1965. if (hasComment) flags += '<span class="text-amber-400 font-bold ml-1" title="Has Comment">C</span>';
  1966. return flags || '<span class="text-slate-600">-</span>';
  1967. }
  1968. function renderActionBadge(action) {
  1969. const act = (action || '').toLowerCase();
  1970. let color = 'bg-slate-800 text-slate-300';
  1971. if (act === 'accept') color = 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30';
  1972. else if (act === 'drop' || act === 'reject') color = 'bg-rose-500/20 text-rose-300 border border-rose-500/30';
  1973. else if (act === 'masquerade' || act === 'src-nat' || act === 'dst-nat') color = 'bg-amber-500/20 text-amber-300 border border-amber-500/30';
  1974. else if (act.startsWith('mark-')) color = 'bg-purple-500/20 text-purple-300 border border-purple-500/30';
  1975. else if (act === 'log') color = 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30';
  1976. return `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold ${color}">${action}</span>`;
  1977. }
  1978. function switchFWSubTab(tab) {
  1979. state.fwSubTab = tab;
  1980. const tabs = ['filter', 'nat', 'mangle', 'addrlist', 'geo', 'connections'];
  1981. tabs.forEach(t => {
  1982. const panel = document.getElementById(`fw-subtab-${t}`);
  1983. const btn = document.getElementById(`fw-subtab-btn-${t}`);
  1984. if (panel) {
  1985. if (t === tab) panel.classList.remove('hidden');
  1986. else panel.classList.add('hidden');
  1987. }
  1988. if (btn) {
  1989. if (t === tab) {
  1990. 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';
  1991. } else {
  1992. 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';
  1993. }
  1994. }
  1995. });
  1996. const addBtn = document.getElementById('fw-primary-add-btn');
  1997. if (addBtn) {
  1998. if (tab === 'filter') addBtn.innerHTML = '<span>+ Add Filter Rule</span>';
  1999. else if (tab === 'nat') addBtn.innerHTML = '<span>+ Add NAT Rule</span>';
  2000. else if (tab === 'mangle') addBtn.innerHTML = '<span>+ Add Mangle Rule</span>';
  2001. else if (tab === 'addrlist') addBtn.innerHTML = '<span>+ Add Address List</span>';
  2002. else if (tab === 'geo') addBtn.innerHTML = '<span>⚙️ Schedule Settings</span>';
  2003. else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
  2004. }
  2005. if (tab === 'geo') loadGeoIP();
  2006. if (tab === 'connections') loadConnections();
  2007. }
  2008. function openCurrentFWModal() {
  2009. if (state.fwSubTab === 'filter') openAddFilterModal();
  2010. else if (state.fwSubTab === 'nat') openAddNATModal();
  2011. else if (state.fwSubTab === 'mangle') openAddMangleModal();
  2012. else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
  2013. else if (state.fwSubTab === 'geo') openGeoIntervalModal();
  2014. else if (state.fwSubTab === 'connections') loadConnections();
  2015. }
  2016. async function loadFirewall(populateDropdowns = true) {
  2017. try {
  2018. const [summaryRes, filterRes, natRes, mangleRes, addrlistRes, geoStatusRes, geoCountriesRes] = await Promise.all([
  2019. fetch(`${API_BASE}/firewall/summary`),
  2020. fetch(`${API_BASE}/firewall/filter`),
  2021. fetch(`${API_BASE}/firewall/nat`),
  2022. fetch(`${API_BASE}/firewall/mangle`),
  2023. fetch(`${API_BASE}/firewall/address-lists`),
  2024. fetch(`${API_BASE}/firewall/geoip/status`),
  2025. fetch(`${API_BASE}/firewall/geoip/countries`)
  2026. ]);
  2027. if (summaryRes.ok) state.fwSummary = await summaryRes.json();
  2028. if (filterRes.ok) state.filterRules = await filterRes.json();
  2029. if (natRes.ok) state.natRules = await natRes.json();
  2030. if (mangleRes.ok) state.mangleRules = await mangleRes.json();
  2031. if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
  2032. if (geoStatusRes.ok) state.geoStatus = await geoStatusRes.json();
  2033. if (geoCountriesRes.ok) state.geoCountries = await geoCountriesRes.json();
  2034. // Badges
  2035. const bFilter = document.getElementById('fw-badge-filter');
  2036. if (bFilter) bFilter.innerText = (state.filterRules || []).length;
  2037. const bNat = document.getElementById('fw-badge-nat');
  2038. if (bNat) bNat.innerText = (state.natRules || []).length;
  2039. const bMangle = document.getElementById('fw-badge-mangle');
  2040. if (bMangle) bMangle.innerText = (state.mangleRules || []).length;
  2041. const bAddr = document.getElementById('fw-badge-addrlist');
  2042. if (bAddr) bAddr.innerText = (state.addressLists || []).length;
  2043. const bGeo = document.getElementById('fw-badge-geo');
  2044. if (bGeo) bGeo.innerText = state.geoStatus?.enabled_count || 0;
  2045. renderFilterRules();
  2046. renderNATRules();
  2047. renderMangleRules();
  2048. renderAddressLists();
  2049. renderGeoCountries();
  2050. if (state.fwSubTab === 'connections') {
  2051. loadConnections();
  2052. }
  2053. } catch (err) {
  2054. console.error('Failed to load firewall:', err);
  2055. }
  2056. }
  2057. // ----------------- Filter Rules -----------------
  2058. function renderFilterRules() {
  2059. const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
  2060. const tbody = document.getElementById('filter-table-body');
  2061. const empty = document.getElementById('filter-empty');
  2062. if (!tbody) return;
  2063. tbody.innerHTML = '';
  2064. const rules = (state.filterRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2065. document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
  2066. if (rules.length === 0) {
  2067. empty?.classList.remove('hidden');
  2068. return;
  2069. }
  2070. empty?.classList.add('hidden');
  2071. rules.forEach((r, idx) => {
  2072. const tr = document.createElement('tr');
  2073. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2074. const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
  2075. const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
  2076. tr.innerHTML = `
  2077. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  2078. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  2079. <td class="py-2.5 px-3 font-bold text-white">${r.chain}</td>
  2080. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  2081. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  2082. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}</td>
  2083. <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
  2084. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  2085. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  2086. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2087. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2088. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2089. </td>
  2090. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2091. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2092. <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2093. <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2094. <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>
  2095. <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2096. <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2097. </td>
  2098. `;
  2099. tbody.appendChild(tr);
  2100. });
  2101. }
  2102. function formatTarget(addr, list, geo) {
  2103. const parts = [];
  2104. if (addr) parts.push(`<span>${addr}</span>`);
  2105. if (list) {
  2106. const inv = list.startsWith('!') ? '!' : '';
  2107. const clean = list.replace(/^!/, '');
  2108. 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>`);
  2109. }
  2110. if (geo) {
  2111. const inv = geo.startsWith('!') ? '!' : '';
  2112. const clean = geo.replace(/^!/, '').replace(/^geo:/, '');
  2113. 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>`);
  2114. }
  2115. if (parts.length === 0) return '<span class="text-slate-600">0.0.0.0/0</span>';
  2116. return parts.join(' ');
  2117. }
  2118. function populateInterfaceSelect(selectId, currentVal = '') {
  2119. const sel = document.getElementById(selectId);
  2120. if (!sel) return;
  2121. sel.innerHTML = '<option value="">(Any Interface)</option>';
  2122. (state.interfaces || []).forEach(i => {
  2123. const opt = document.createElement('option');
  2124. opt.value = i.name;
  2125. opt.innerText = `${i.name} (${i.role || i.type})`;
  2126. if (i.name === currentVal) opt.selected = true;
  2127. sel.appendChild(opt);
  2128. });
  2129. }
  2130. function populateAddressListSelect(selectId, currentVal = '') {
  2131. const sel = document.getElementById(selectId);
  2132. if (!sel) return;
  2133. sel.innerHTML = '<option value="">(None)</option>';
  2134. const cleanVal = (currentVal || '').replace(/^!/, '');
  2135. const customNames = Array.from(new Set((state.addressLists || []).map(a => a.name))).sort();
  2136. customNames.forEach(name => {
  2137. const count = (state.addressLists || []).filter(a => a.name === name).length;
  2138. const opt = document.createElement('option');
  2139. opt.value = name;
  2140. opt.innerText = `${name} (${count} entries)`;
  2141. if (name === cleanVal) opt.selected = true;
  2142. sel.appendChild(opt);
  2143. });
  2144. if (cleanVal && !sel.querySelector(`option[value="${cleanVal}"]`)) {
  2145. const opt = document.createElement('option');
  2146. opt.value = cleanVal;
  2147. opt.innerText = cleanVal;
  2148. opt.selected = true;
  2149. sel.appendChild(opt);
  2150. }
  2151. }
  2152. function populateGeoIPSelect(selectId, currentVal = '') {
  2153. const sel = document.getElementById(selectId);
  2154. if (!sel) return;
  2155. sel.innerHTML = '<option value="">(None)</option>';
  2156. const cleanVal = (currentVal || '').replace(/^!/, '').replace(/^geo:/, '').toUpperCase();
  2157. // Presets optgroup
  2158. const grpPresets = document.createElement('optgroup');
  2159. grpPresets.label = '⚡ Regional Presets';
  2160. const presets = [
  2161. { code: 'EU', label: '🇪🇺 European Union (EU - 27 countries)' },
  2162. { code: 'BALKANS', label: '🏛️ Balkans (GR, CY, BG, RO, AL, etc.)' },
  2163. { code: 'BLOCKLIST', label: '🛡️ High-Risk Blocklist (CN, RU, IR, KP, BY)' }
  2164. ];
  2165. presets.forEach(p => {
  2166. const opt = document.createElement('option');
  2167. opt.value = p.code;
  2168. opt.innerText = p.label;
  2169. if (p.code === cleanVal) opt.selected = true;
  2170. grpPresets.appendChild(opt);
  2171. });
  2172. sel.appendChild(grpPresets);
  2173. // All Countries optgroup
  2174. const grpCountries = document.createElement('optgroup');
  2175. grpCountries.label = '🌍 All Countries';
  2176. const countries = (state.geoCountries || []).slice().sort((a, b) => a.name.localeCompare(b.name));
  2177. countries.forEach(c => {
  2178. const opt = document.createElement('option');
  2179. opt.value = c.code;
  2180. const subnetsInfo = c.subnet_count ? ` [${c.subnet_count.toLocaleString()} subnets]` : '';
  2181. opt.innerText = `${c.name} (${c.code})${subnetsInfo}`;
  2182. if (c.code === cleanVal) opt.selected = true;
  2183. grpCountries.appendChild(opt);
  2184. });
  2185. sel.appendChild(grpCountries);
  2186. }
  2187. function openAddFilterModal() {
  2188. document.getElementById('filter-modal-title').innerText = 'Add Firewall Filter Rule';
  2189. document.getElementById('filter-modal-id').value = '';
  2190. document.getElementById('filter-modal-chain').value = 'forward';
  2191. document.getElementById('filter-modal-action').value = 'accept';
  2192. document.getElementById('filter-modal-proto').value = 'all';
  2193. document.getElementById('filter-modal-src').value = '';
  2194. document.getElementById('filter-modal-dst').value = '';
  2195. document.getElementById('filter-modal-sport').value = '';
  2196. document.getElementById('filter-modal-dport').value = '';
  2197. document.getElementById('filter-modal-connmark').value = '';
  2198. document.getElementById('filter-modal-comment').value = '';
  2199. document.getElementById('filter-modal-disabled').checked = false;
  2200. document.getElementById('filter-modal-cs-established').checked = false;
  2201. document.getElementById('filter-modal-cs-related').checked = false;
  2202. document.getElementById('filter-modal-cs-new').checked = false;
  2203. document.getElementById('filter-modal-cs-invalid').checked = false;
  2204. populateInterfaceSelect('filter-modal-iniface');
  2205. populateInterfaceSelect('filter-modal-outiface');
  2206. if (document.getElementById('filter-modal-srclist-inv')) document.getElementById('filter-modal-srclist-inv').checked = false;
  2207. if (document.getElementById('filter-modal-dstlist-inv')) document.getElementById('filter-modal-dstlist-inv').checked = false;
  2208. populateAddressListSelect('filter-modal-srclist');
  2209. populateAddressListSelect('filter-modal-dstlist');
  2210. if (document.getElementById('filter-modal-srcgeoip-inv')) document.getElementById('filter-modal-srcgeoip-inv').checked = false;
  2211. if (document.getElementById('filter-modal-dstgeoip-inv')) document.getElementById('filter-modal-dstgeoip-inv').checked = false;
  2212. populateGeoIPSelect('filter-modal-srcgeoip');
  2213. populateGeoIPSelect('filter-modal-dstgeoip');
  2214. toggleFilterActionFields();
  2215. document.getElementById('filter-modal').classList.remove('hidden');
  2216. }
  2217. function openEditFilterModal(id) {
  2218. const r = (state.filterRules || []).find(rule => rule.id === id);
  2219. if (!r) return;
  2220. document.getElementById('filter-modal-title').innerText = `Edit Filter Rule (#${r.order})`;
  2221. document.getElementById('filter-modal-id').value = r.id;
  2222. document.getElementById('filter-modal-chain').value = r.chain || 'forward';
  2223. document.getElementById('filter-modal-action').value = r.action || 'accept';
  2224. document.getElementById('filter-modal-proto').value = r.protocol || 'all';
  2225. document.getElementById('filter-modal-src').value = r.src_address || '';
  2226. document.getElementById('filter-modal-dst').value = r.dst_address || '';
  2227. document.getElementById('filter-modal-sport').value = r.src_port || '';
  2228. document.getElementById('filter-modal-dport').value = r.dst_port || '';
  2229. document.getElementById('filter-modal-connmark').value = r.connection_mark || '';
  2230. document.getElementById('filter-modal-comment').value = r.comment || '';
  2231. document.getElementById('filter-modal-disabled').checked = !!r.disabled;
  2232. const states = r.connection_state || [];
  2233. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  2234. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  2235. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  2236. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  2237. populateInterfaceSelect('filter-modal-iniface', r.in_interface);
  2238. populateInterfaceSelect('filter-modal-outiface', r.out_interface);
  2239. const srcInv = (r.src_address_list || '').startsWith('!');
  2240. const dstInv = (r.dst_address_list || '').startsWith('!');
  2241. if (document.getElementById('filter-modal-srclist-inv')) document.getElementById('filter-modal-srclist-inv').checked = srcInv;
  2242. if (document.getElementById('filter-modal-dstlist-inv')) document.getElementById('filter-modal-dstlist-inv').checked = dstInv;
  2243. populateAddressListSelect('filter-modal-srclist', r.src_address_list || '');
  2244. populateAddressListSelect('filter-modal-dstlist', r.dst_address_list || '');
  2245. const srcGeoInv = (r.src_geoip || '').startsWith('!');
  2246. const dstGeoInv = (r.dst_geoip || '').startsWith('!');
  2247. if (document.getElementById('filter-modal-srcgeoip-inv')) document.getElementById('filter-modal-srcgeoip-inv').checked = srcGeoInv;
  2248. if (document.getElementById('filter-modal-dstgeoip-inv')) document.getElementById('filter-modal-dstgeoip-inv').checked = dstGeoInv;
  2249. populateGeoIPSelect('filter-modal-srcgeoip', r.src_geoip || '');
  2250. populateGeoIPSelect('filter-modal-dstgeoip', r.dst_geoip || '');
  2251. toggleFilterActionFields();
  2252. document.getElementById('filter-modal').classList.remove('hidden');
  2253. }
  2254. function closeFilterModal() {
  2255. document.getElementById('filter-modal').classList.add('hidden');
  2256. }
  2257. function toggleFilterActionFields() {
  2258. const act = document.getElementById('filter-modal-action').value;
  2259. const rejectBox = document.getElementById('filter-action-reject-box');
  2260. if (rejectBox) {
  2261. if (act === 'reject') rejectBox.classList.remove('hidden');
  2262. else rejectBox.classList.add('hidden');
  2263. }
  2264. }
  2265. async function submitSaveFilterRule(e) {
  2266. e.preventDefault();
  2267. const id = document.getElementById('filter-modal-id').value;
  2268. const chain = document.getElementById('filter-modal-chain').value;
  2269. const action = document.getElementById('filter-modal-action').value;
  2270. const proto = document.getElementById('filter-modal-proto').value;
  2271. const src = document.getElementById('filter-modal-src').value.trim();
  2272. const dst = document.getElementById('filter-modal-dst').value.trim();
  2273. const sport = document.getElementById('filter-modal-sport').value.trim();
  2274. const dport = document.getElementById('filter-modal-dport').value.trim();
  2275. const inIface = document.getElementById('filter-modal-iniface').value;
  2276. const outIface = document.getElementById('filter-modal-outiface').value;
  2277. const connmark = document.getElementById('filter-modal-connmark').value.trim();
  2278. let srclist = document.getElementById('filter-modal-srclist')?.value || '';
  2279. if (srclist && document.getElementById('filter-modal-srclist-inv')?.checked) {
  2280. srclist = '!' + srclist.replace(/^!/, '');
  2281. }
  2282. let dstlist = document.getElementById('filter-modal-dstlist')?.value || '';
  2283. if (dstlist && document.getElementById('filter-modal-dstlist-inv')?.checked) {
  2284. dstlist = '!' + dstlist.replace(/^!/, '');
  2285. }
  2286. let srcgeoip = document.getElementById('filter-modal-srcgeoip')?.value || '';
  2287. if (srcgeoip && document.getElementById('filter-modal-srcgeoip-inv')?.checked) {
  2288. srcgeoip = '!' + srcgeoip.replace(/^!/, '');
  2289. }
  2290. let dstgeoip = document.getElementById('filter-modal-dstgeoip')?.value || '';
  2291. if (dstgeoip && document.getElementById('filter-modal-dstgeoip-inv')?.checked) {
  2292. dstgeoip = '!' + dstgeoip.replace(/^!/, '');
  2293. }
  2294. const comment = document.getElementById('filter-modal-comment').value.trim();
  2295. const disabled = document.getElementById('filter-modal-disabled').checked;
  2296. const rejectWith = document.getElementById('filter-modal-rejectwith')?.value || '';
  2297. const states = [];
  2298. if (document.getElementById('filter-modal-cs-established').checked) states.push('established');
  2299. if (document.getElementById('filter-modal-cs-related').checked) states.push('related');
  2300. if (document.getElementById('filter-modal-cs-new').checked) states.push('new');
  2301. if (document.getElementById('filter-modal-cs-invalid').checked) states.push('invalid');
  2302. try {
  2303. const res = await fetch(`${API_BASE}/firewall/filter`, {
  2304. method: 'POST',
  2305. headers: { 'Content-Type': 'application/json' },
  2306. body: JSON.stringify({
  2307. id,
  2308. chain,
  2309. action,
  2310. reject_with: rejectWith,
  2311. protocol: proto,
  2312. src_address: src,
  2313. dst_address: dst,
  2314. src_port: sport,
  2315. dst_port: dport,
  2316. in_interface: inIface,
  2317. out_interface: outIface,
  2318. connection_state: states,
  2319. connection_mark: connmark,
  2320. src_address_list: srclist,
  2321. dst_address_list: dstlist,
  2322. src_geoip: srcgeoip,
  2323. dst_geoip: dstgeoip,
  2324. comment,
  2325. disabled
  2326. })
  2327. });
  2328. if (res.ok) {
  2329. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  2330. closeFilterModal();
  2331. loadFirewall(false);
  2332. } else {
  2333. const err = await res.json();
  2334. showToast('Error', err.message, 'error');
  2335. }
  2336. } catch (err) {
  2337. showToast('Error', err.message, 'error');
  2338. }
  2339. }
  2340. async function moveFilterRule(id, dir) {
  2341. try {
  2342. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  2343. method: 'POST',
  2344. headers: { 'Content-Type': 'application/json' },
  2345. body: JSON.stringify({ direction: dir })
  2346. });
  2347. if (res.ok) loadFirewall(false);
  2348. } catch (err) {
  2349. showToast('Error', err.message, 'error');
  2350. }
  2351. }
  2352. async function toggleFilterRuleState(id, disabled) {
  2353. try {
  2354. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  2355. method: 'POST',
  2356. headers: { 'Content-Type': 'application/json' },
  2357. body: JSON.stringify({ disabled })
  2358. });
  2359. if (res.ok) loadFirewall(false);
  2360. } catch (err) {
  2361. showToast('Error', err.message, 'error');
  2362. }
  2363. }
  2364. async function deleteFilterRule(id) {
  2365. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  2366. try {
  2367. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  2368. if (res.ok) {
  2369. showToast('Deleted', 'Filter rule removed', 'success');
  2370. loadFirewall(false);
  2371. }
  2372. } catch (err) {
  2373. showToast('Error', err.message, 'error');
  2374. }
  2375. }
  2376. // ----------------- NAT Rules -----------------
  2377. function renderNATRules() {
  2378. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  2379. const tbody = document.getElementById('nat-table-body');
  2380. const empty = document.getElementById('nat-empty');
  2381. if (!tbody) return;
  2382. tbody.innerHTML = '';
  2383. const rules = (state.natRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2384. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  2385. if (rules.length === 0) {
  2386. empty?.classList.remove('hidden');
  2387. return;
  2388. }
  2389. empty?.classList.add('hidden');
  2390. rules.forEach((r, idx) => {
  2391. const tr = document.createElement('tr');
  2392. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2393. const toTarget = [r.to_addresses, r.to_ports].filter(Boolean).join(':');
  2394. const ifaces = [r.out_interface ? 'out:' + r.out_interface : '', r.in_interface ? 'in:' + r.in_interface : ''].filter(Boolean).join(' ');
  2395. tr.innerHTML = `
  2396. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  2397. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  2398. <td class="py-2.5 px-3 font-bold text-amber-400">${r.chain}</td>
  2399. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  2400. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  2401. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}${r.dst_port ? ':' + r.dst_port : ''}</td>
  2402. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  2403. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  2404. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${toTarget || '-'}</td>
  2405. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2406. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2407. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2408. </td>
  2409. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2410. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2411. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2412. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2413. <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>
  2414. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2415. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2416. </td>
  2417. `;
  2418. tbody.appendChild(tr);
  2419. });
  2420. }
  2421. function openAddNATModal() {
  2422. document.getElementById('nat-modal-title').innerText = 'Add NAT Rule';
  2423. document.getElementById('nat-modal-id').value = '';
  2424. document.getElementById('nat-modal-chain').value = 'srcnat';
  2425. document.getElementById('nat-modal-action').value = 'masquerade';
  2426. document.getElementById('nat-modal-toaddr').value = '';
  2427. document.getElementById('nat-modal-toport').value = '';
  2428. document.getElementById('nat-modal-proto').value = 'all';
  2429. document.getElementById('nat-modal-src').value = '';
  2430. document.getElementById('nat-modal-dst').value = '';
  2431. document.getElementById('nat-modal-dport').value = '';
  2432. document.getElementById('nat-modal-comment').value = '';
  2433. document.getElementById('nat-modal-disabled').checked = false;
  2434. populateInterfaceSelect('nat-modal-iniface');
  2435. populateInterfaceSelect('nat-modal-outiface');
  2436. populateAddressListSelect('nat-modal-srclist');
  2437. populateAddressListSelect('nat-modal-dstlist');
  2438. const srcInvEl = document.getElementById('nat-modal-srclist-inv');
  2439. if (srcInvEl) srcInvEl.checked = false;
  2440. const dstInvEl = document.getElementById('nat-modal-dstlist-inv');
  2441. if (dstInvEl) dstInvEl.checked = false;
  2442. populateGeoIPSelect('nat-modal-srcgeoip');
  2443. populateGeoIPSelect('nat-modal-dstgeoip');
  2444. const srcGeoInvEl = document.getElementById('nat-modal-srcgeoip-inv');
  2445. if (srcGeoInvEl) srcGeoInvEl.checked = false;
  2446. const dstGeoInvEl = document.getElementById('nat-modal-dstgeoip-inv');
  2447. if (dstGeoInvEl) dstGeoInvEl.checked = false;
  2448. toggleNATActionFields();
  2449. document.getElementById('nat-modal').classList.remove('hidden');
  2450. }
  2451. function openEditNATModal(id) {
  2452. const r = (state.natRules || []).find(rule => rule.id === id);
  2453. if (!r) return;
  2454. document.getElementById('nat-modal-title').innerText = `Edit NAT Rule (#${r.order})`;
  2455. document.getElementById('nat-modal-id').value = r.id;
  2456. document.getElementById('nat-modal-chain').value = r.chain || 'srcnat';
  2457. document.getElementById('nat-modal-action').value = r.action || 'masquerade';
  2458. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  2459. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  2460. document.getElementById('nat-modal-proto').value = r.protocol || 'all';
  2461. document.getElementById('nat-modal-src').value = r.src_address || '';
  2462. document.getElementById('nat-modal-dst').value = r.dst_address || '';
  2463. document.getElementById('nat-modal-dport').value = r.dst_port || '';
  2464. document.getElementById('nat-modal-comment').value = r.comment || '';
  2465. document.getElementById('nat-modal-disabled').checked = !!r.disabled;
  2466. populateInterfaceSelect('nat-modal-iniface', r.in_interface);
  2467. populateInterfaceSelect('nat-modal-outiface', r.out_interface);
  2468. const srcInv = (r.src_address_list || '').startsWith('!');
  2469. const dstInv = (r.dst_address_list || '').startsWith('!');
  2470. const srcInvEl = document.getElementById('nat-modal-srclist-inv');
  2471. if (srcInvEl) srcInvEl.checked = srcInv;
  2472. const dstInvEl = document.getElementById('nat-modal-dstlist-inv');
  2473. if (dstInvEl) dstInvEl.checked = dstInv;
  2474. populateAddressListSelect('nat-modal-srclist', r.src_address_list || '');
  2475. populateAddressListSelect('nat-modal-dstlist', r.dst_address_list || '');
  2476. const srcGeoInv = (r.src_geoip || '').startsWith('!');
  2477. const dstGeoInv = (r.dst_geoip || '').startsWith('!');
  2478. const srcGeoInvEl = document.getElementById('nat-modal-srcgeoip-inv');
  2479. if (srcGeoInvEl) srcGeoInvEl.checked = srcGeoInv;
  2480. const dstGeoInvEl = document.getElementById('nat-modal-dstgeoip-inv');
  2481. if (dstGeoInvEl) dstGeoInvEl.checked = dstGeoInv;
  2482. populateGeoIPSelect('nat-modal-srcgeoip', r.src_geoip || '');
  2483. populateGeoIPSelect('nat-modal-dstgeoip', r.dst_geoip || '');
  2484. toggleNATActionFields();
  2485. document.getElementById('nat-modal').classList.remove('hidden');
  2486. }
  2487. function closeNATModal() {
  2488. document.getElementById('nat-modal').classList.add('hidden');
  2489. }
  2490. function toggleNATChainFields() {
  2491. const ch = document.getElementById('nat-modal-chain').value;
  2492. const actSel = document.getElementById('nat-modal-action');
  2493. if (ch === 'srcnat' && actSel.value === 'dst-nat') {
  2494. actSel.value = 'masquerade';
  2495. } else if (ch === 'dstnat' && actSel.value === 'masquerade') {
  2496. actSel.value = 'dst-nat';
  2497. }
  2498. toggleNATActionFields();
  2499. }
  2500. function toggleNATActionFields() {
  2501. const act = document.getElementById('nat-modal-action').value;
  2502. const toBox = document.getElementById('nat-action-to-box');
  2503. if (toBox) {
  2504. if (act === 'masquerade' || act === 'accept') toBox.classList.add('hidden');
  2505. else toBox.classList.remove('hidden');
  2506. }
  2507. }
  2508. async function submitSaveNATRule(e) {
  2509. e.preventDefault();
  2510. const id = document.getElementById('nat-modal-id').value;
  2511. const chain = document.getElementById('nat-modal-chain').value;
  2512. const action = document.getElementById('nat-modal-action').value;
  2513. const toaddr = document.getElementById('nat-modal-toaddr').value.trim();
  2514. const toport = document.getElementById('nat-modal-toport').value.trim();
  2515. const proto = document.getElementById('nat-modal-proto').value;
  2516. const src = document.getElementById('nat-modal-src').value.trim();
  2517. const dst = document.getElementById('nat-modal-dst').value.trim();
  2518. const dport = document.getElementById('nat-modal-dport').value.trim();
  2519. const inIface = document.getElementById('nat-modal-iniface').value;
  2520. const outIface = document.getElementById('nat-modal-outiface').value;
  2521. let srclist = document.getElementById('nat-modal-srclist')?.value || '';
  2522. if (srclist && document.getElementById('nat-modal-srclist-inv')?.checked) {
  2523. srclist = '!' + srclist.replace(/^!/, '');
  2524. }
  2525. let dstlist = document.getElementById('nat-modal-dstlist')?.value || '';
  2526. if (dstlist && document.getElementById('nat-modal-dstlist-inv')?.checked) {
  2527. dstlist = '!' + dstlist.replace(/^!/, '');
  2528. }
  2529. let srcgeoip = document.getElementById('nat-modal-srcgeoip')?.value || '';
  2530. if (srcgeoip && document.getElementById('nat-modal-srcgeoip-inv')?.checked) {
  2531. srcgeoip = '!' + srcgeoip.replace(/^!/, '');
  2532. }
  2533. let dstgeoip = document.getElementById('nat-modal-dstgeoip')?.value || '';
  2534. if (dstgeoip && document.getElementById('nat-modal-dstgeoip-inv')?.checked) {
  2535. dstgeoip = '!' + dstgeoip.replace(/^!/, '');
  2536. }
  2537. const comment = document.getElementById('nat-modal-comment').value.trim();
  2538. const disabled = document.getElementById('nat-modal-disabled').checked;
  2539. try {
  2540. const res = await fetch(`${API_BASE}/firewall/nat`, {
  2541. method: 'POST',
  2542. headers: { 'Content-Type': 'application/json' },
  2543. body: JSON.stringify({
  2544. id,
  2545. chain,
  2546. action,
  2547. to_addresses: toaddr,
  2548. to_ports: toport,
  2549. protocol: proto,
  2550. src_address: src,
  2551. dst_address: dst,
  2552. dst_port: dport,
  2553. in_interface: inIface,
  2554. out_interface: outIface,
  2555. src_address_list: srclist,
  2556. dst_address_list: dstlist,
  2557. src_geoip: srcgeoip,
  2558. dst_geoip: dstgeoip,
  2559. comment,
  2560. disabled
  2561. })
  2562. });
  2563. if (res.ok) {
  2564. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  2565. closeNATModal();
  2566. loadFirewall(false);
  2567. }
  2568. } catch (err) {
  2569. showToast('Error', err.message, 'error');
  2570. }
  2571. }
  2572. async function moveNATRule(id, dir) {
  2573. try {
  2574. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  2575. method: 'POST',
  2576. headers: { 'Content-Type': 'application/json' },
  2577. body: JSON.stringify({ direction: dir })
  2578. });
  2579. if (res.ok) loadFirewall(false);
  2580. } catch (err) {
  2581. showToast('Error', err.message, 'error');
  2582. }
  2583. }
  2584. async function toggleNATRuleState(id, disabled) {
  2585. try {
  2586. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  2587. method: 'POST',
  2588. headers: { 'Content-Type': 'application/json' },
  2589. body: JSON.stringify({ disabled })
  2590. });
  2591. if (res.ok) loadFirewall(false);
  2592. } catch (err) {
  2593. showToast('Error', err.message, 'error');
  2594. }
  2595. }
  2596. async function deleteNATRule(id) {
  2597. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  2598. try {
  2599. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  2600. if (res.ok) {
  2601. showToast('Deleted', 'NAT rule removed', 'success');
  2602. loadFirewall(false);
  2603. }
  2604. } catch (err) {
  2605. showToast('Error', err.message, 'error');
  2606. }
  2607. }
  2608. // ----------------- Mangle Rules -----------------
  2609. function renderMangleRules() {
  2610. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  2611. const tbody = document.getElementById('mangle-table-body');
  2612. const empty = document.getElementById('mangle-empty');
  2613. if (!tbody) return;
  2614. tbody.innerHTML = '';
  2615. const rules = (state.mangleRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2616. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  2617. if (rules.length === 0) {
  2618. empty?.classList.remove('hidden');
  2619. return;
  2620. }
  2621. empty?.classList.add('hidden');
  2622. rules.forEach((r, idx) => {
  2623. const tr = document.createElement('tr');
  2624. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2625. const markVal = r.new_connection_mark || r.new_routing_mark || r.new_packet_mark || r.new_mss || (r.new_dscp ? 'DSCP:' + r.new_dscp : '');
  2626. tr.innerHTML = `
  2627. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  2628. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  2629. <td class="py-2.5 px-3 font-bold text-purple-400">${r.chain}</td>
  2630. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  2631. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  2632. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  2633. <td class="py-2.5 px-3 font-mono font-bold text-cyan-300">${markVal || '-'}</td>
  2634. <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>
  2635. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2636. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2637. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2638. </td>
  2639. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2640. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2641. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2642. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2643. <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>
  2644. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2645. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2646. </td>
  2647. `;
  2648. tbody.appendChild(tr);
  2649. });
  2650. }
  2651. function openAddMangleModal() {
  2652. document.getElementById('mangle-modal-title').innerText = 'Add Mangle Rule';
  2653. document.getElementById('mangle-modal-id').value = '';
  2654. document.getElementById('mangle-modal-chain').value = 'prerouting';
  2655. document.getElementById('mangle-modal-action').value = 'mark-connection';
  2656. document.getElementById('mangle-modal-newmark').value = '';
  2657. document.getElementById('mangle-modal-passthrough').checked = true;
  2658. document.getElementById('mangle-modal-src').value = '';
  2659. document.getElementById('mangle-modal-dst').value = '';
  2660. document.getElementById('mangle-modal-connmark').value = '';
  2661. document.getElementById('mangle-modal-comment').value = '';
  2662. document.getElementById('mangle-modal-disabled').checked = false;
  2663. populateInterfaceSelect('mangle-modal-iniface');
  2664. populateAddressListSelect('mangle-modal-srclist');
  2665. populateAddressListSelect('mangle-modal-dstlist');
  2666. const srcInvEl = document.getElementById('mangle-modal-srclist-inv');
  2667. if (srcInvEl) srcInvEl.checked = false;
  2668. const dstInvEl = document.getElementById('mangle-modal-dstlist-inv');
  2669. if (dstInvEl) dstInvEl.checked = false;
  2670. populateGeoIPSelect('mangle-modal-srcgeoip');
  2671. populateGeoIPSelect('mangle-modal-dstgeoip');
  2672. const srcGeoInvEl = document.getElementById('mangle-modal-srcgeoip-inv');
  2673. if (srcGeoInvEl) srcGeoInvEl.checked = false;
  2674. const dstGeoInvEl = document.getElementById('mangle-modal-dstgeoip-inv');
  2675. if (dstGeoInvEl) dstGeoInvEl.checked = false;
  2676. document.getElementById('mangle-modal').classList.remove('hidden');
  2677. }
  2678. function openEditMangleModal(id) {
  2679. const r = (state.mangleRules || []).find(rule => rule.id === id);
  2680. if (!r) return;
  2681. document.getElementById('mangle-modal-title').innerText = `Edit Mangle Rule (#${r.order})`;
  2682. document.getElementById('mangle-modal-id').value = r.id;
  2683. document.getElementById('mangle-modal-chain').value = r.chain || 'prerouting';
  2684. document.getElementById('mangle-modal-action').value = r.action || 'mark-connection';
  2685. document.getElementById('mangle-modal-newmark').value = r.new_connection_mark || r.new_routing_mark || r.new_packet_mark || r.new_mss || '';
  2686. document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  2687. document.getElementById('mangle-modal-src').value = r.src_address || '';
  2688. document.getElementById('mangle-modal-dst').value = r.dst_address || '';
  2689. document.getElementById('mangle-modal-connmark').value = r.connection_mark || '';
  2690. document.getElementById('mangle-modal-comment').value = r.comment || '';
  2691. document.getElementById('mangle-modal-disabled').checked = !!r.disabled;
  2692. populateInterfaceSelect('mangle-modal-iniface', r.in_interface);
  2693. const srcInv = (r.src_address_list || '').startsWith('!');
  2694. const dstInv = (r.dst_address_list || '').startsWith('!');
  2695. const srcInvEl = document.getElementById('mangle-modal-srclist-inv');
  2696. if (srcInvEl) srcInvEl.checked = srcInv;
  2697. const dstInvEl = document.getElementById('mangle-modal-dstlist-inv');
  2698. if (dstInvEl) dstInvEl.checked = dstInv;
  2699. populateAddressListSelect('mangle-modal-srclist', r.src_address_list || '');
  2700. populateAddressListSelect('mangle-modal-dstlist', r.dst_address_list || '');
  2701. const srcGeoInv = (r.src_geoip || '').startsWith('!');
  2702. const dstGeoInv = (r.dst_geoip || '').startsWith('!');
  2703. const srcGeoInvEl = document.getElementById('mangle-modal-srcgeoip-inv');
  2704. if (srcGeoInvEl) srcGeoInvEl.checked = srcGeoInv;
  2705. const dstGeoInvEl = document.getElementById('mangle-modal-dstgeoip-inv');
  2706. if (dstGeoInvEl) dstGeoInvEl.checked = dstGeoInv;
  2707. populateGeoIPSelect('mangle-modal-srcgeoip', r.src_geoip || '');
  2708. populateGeoIPSelect('mangle-modal-dstgeoip', r.dst_geoip || '');
  2709. document.getElementById('mangle-modal').classList.remove('hidden');
  2710. }
  2711. function closeMangleModal() {
  2712. document.getElementById('mangle-modal').classList.add('hidden');
  2713. }
  2714. function toggleMangleActionFields() {
  2715. // Handled smoothly by single dynamic input
  2716. }
  2717. async function submitSaveMangleRule(e) {
  2718. e.preventDefault();
  2719. const id = document.getElementById('mangle-modal-id').value;
  2720. const chain = document.getElementById('mangle-modal-chain').value;
  2721. const action = document.getElementById('mangle-modal-action').value;
  2722. const newmark = document.getElementById('mangle-modal-newmark').value.trim();
  2723. const passthrough = document.getElementById('mangle-modal-passthrough').checked;
  2724. const src = document.getElementById('mangle-modal-src').value.trim();
  2725. const dst = document.getElementById('mangle-modal-dst').value.trim();
  2726. const inIface = document.getElementById('mangle-modal-iniface').value;
  2727. let srclist = document.getElementById('mangle-modal-srclist')?.value || '';
  2728. if (srclist && document.getElementById('mangle-modal-srclist-inv')?.checked) {
  2729. srclist = '!' + srclist.replace(/^!/, '');
  2730. }
  2731. let dstlist = document.getElementById('mangle-modal-dstlist')?.value || '';
  2732. if (dstlist && document.getElementById('mangle-modal-dstlist-inv')?.checked) {
  2733. dstlist = '!' + dstlist.replace(/^!/, '');
  2734. }
  2735. let srcgeoip = document.getElementById('mangle-modal-srcgeoip')?.value || '';
  2736. if (srcgeoip && document.getElementById('mangle-modal-srcgeoip-inv')?.checked) {
  2737. srcgeoip = '!' + srcgeoip.replace(/^!/, '');
  2738. }
  2739. let dstgeoip = document.getElementById('mangle-modal-dstgeoip')?.value || '';
  2740. if (dstgeoip && document.getElementById('mangle-modal-dstgeoip-inv')?.checked) {
  2741. dstgeoip = '!' + dstgeoip.replace(/^!/, '');
  2742. }
  2743. const connmark = document.getElementById('mangle-modal-connmark').value.trim();
  2744. const comment = document.getElementById('mangle-modal-comment').value.trim();
  2745. const disabled = document.getElementById('mangle-modal-disabled').checked;
  2746. const payload = {
  2747. id,
  2748. chain,
  2749. action,
  2750. passthrough,
  2751. src_address: src,
  2752. dst_address: dst,
  2753. in_interface: inIface,
  2754. src_address_list: srclist,
  2755. dst_address_list: dstlist,
  2756. src_geoip: srcgeoip,
  2757. dst_geoip: dstgeoip,
  2758. connection_mark: connmark,
  2759. comment,
  2760. disabled
  2761. };
  2762. if (action === 'mark-connection') payload.new_connection_mark = newmark;
  2763. else if (action === 'mark-routing') payload.new_routing_mark = newmark;
  2764. else if (action === 'mark-packet') payload.new_packet_mark = newmark;
  2765. else if (action === 'change-mss') payload.new_mss = newmark || 'clamp-to-pmtu';
  2766. try {
  2767. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  2768. method: 'POST',
  2769. headers: { 'Content-Type': 'application/json' },
  2770. body: JSON.stringify(payload)
  2771. });
  2772. if (res.ok) {
  2773. showToast('Mangle Rule Saved', 'Marking rule applied', 'success');
  2774. closeMangleModal();
  2775. loadFirewall(false);
  2776. }
  2777. } catch (err) {
  2778. showToast('Error', err.message, 'error');
  2779. }
  2780. }
  2781. async function moveMangleRule(id, dir) {
  2782. try {
  2783. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  2784. method: 'POST',
  2785. headers: { 'Content-Type': 'application/json' },
  2786. body: JSON.stringify({ direction: dir })
  2787. });
  2788. if (res.ok) loadFirewall(false);
  2789. } catch (err) {
  2790. showToast('Error', err.message, 'error');
  2791. }
  2792. }
  2793. async function toggleMangleRuleState(id, disabled) {
  2794. try {
  2795. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  2796. method: 'POST',
  2797. headers: { 'Content-Type': 'application/json' },
  2798. body: JSON.stringify({ disabled })
  2799. });
  2800. if (res.ok) loadFirewall(false);
  2801. } catch (err) {
  2802. showToast('Error', err.message, 'error');
  2803. }
  2804. }
  2805. async function deleteMangleRule(id) {
  2806. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  2807. try {
  2808. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  2809. if (res.ok) {
  2810. showToast('Deleted', 'Mangle rule removed', 'success');
  2811. loadFirewall(false);
  2812. }
  2813. } catch (err) {
  2814. showToast('Error', err.message, 'error');
  2815. }
  2816. }
  2817. // ----------------- Address Lists -----------------
  2818. function renderAddressLists() {
  2819. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  2820. const tbody = document.getElementById('addrlist-table-body');
  2821. const empty = document.getElementById('addrlist-empty');
  2822. if (!tbody) return;
  2823. tbody.innerHTML = '';
  2824. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  2825. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries`;
  2826. // Update filter select
  2827. const sel = document.getElementById('addrlist-filter-name');
  2828. if (sel) {
  2829. const cur = sel.value;
  2830. sel.innerHTML = '<option value="">All Lists</option>';
  2831. const set = new Set((state.addressLists || []).map(a => a.name));
  2832. set.forEach(n => {
  2833. const opt = document.createElement('option');
  2834. opt.value = n;
  2835. opt.innerText = n;
  2836. if (n === cur) opt.selected = true;
  2837. sel.appendChild(opt);
  2838. });
  2839. }
  2840. if (entries.length === 0) {
  2841. empty?.classList.remove('hidden');
  2842. return;
  2843. }
  2844. empty?.classList.add('hidden');
  2845. entries.forEach((e, idx) => {
  2846. const tr = document.createElement('tr');
  2847. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
  2848. tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
  2849. tr.innerHTML = `
  2850. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  2851. <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>
  2852. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  2853. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  2854. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]">${e.comment || '-'}</td>
  2855. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  2856. <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>
  2857. <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
  2858. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2859. </td>
  2860. `;
  2861. tbody.appendChild(tr);
  2862. });
  2863. }
  2864. function openAddAddrListModal() {
  2865. document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
  2866. document.getElementById('addrlist-modal-id').value = '';
  2867. document.getElementById('addrlist-modal-name').value = '';
  2868. document.getElementById('addrlist-modal-addr').value = '';
  2869. document.getElementById('addrlist-modal-comment').value = '';
  2870. document.getElementById('addrlist-modal-disabled').checked = false;
  2871. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  2872. if (submitBtn) submitBtn.innerText = 'Add to List';
  2873. document.getElementById('addrlist-modal').classList.remove('hidden');
  2874. }
  2875. function openEditAddrListModal(id) {
  2876. const e = (state.addressLists || []).find(item => item.id === id);
  2877. if (!e) return;
  2878. document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
  2879. document.getElementById('addrlist-modal-id').value = e.id;
  2880. document.getElementById('addrlist-modal-name').value = e.name;
  2881. document.getElementById('addrlist-modal-addr').value = e.address;
  2882. document.getElementById('addrlist-modal-comment').value = e.comment || '';
  2883. document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
  2884. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  2885. if (submitBtn) submitBtn.innerText = 'Save Changes';
  2886. document.getElementById('addrlist-modal').classList.remove('hidden');
  2887. }
  2888. function closeAddrListModal() {
  2889. document.getElementById('addrlist-modal').classList.add('hidden');
  2890. }
  2891. async function submitSaveAddrList(e) {
  2892. e.preventDefault();
  2893. const id = document.getElementById('addrlist-modal-id').value;
  2894. const name = document.getElementById('addrlist-modal-name').value.trim();
  2895. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  2896. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  2897. const disabled = document.getElementById('addrlist-modal-disabled').checked;
  2898. try {
  2899. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  2900. method: 'POST',
  2901. headers: { 'Content-Type': 'application/json' },
  2902. body: JSON.stringify({ id, name, address: addr, comment, disabled })
  2903. });
  2904. if (res.ok) {
  2905. showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
  2906. closeAddrListModal();
  2907. loadFirewall(false);
  2908. } else {
  2909. const err = await res.json();
  2910. showToast('Error', err.message || 'Failed to save address list', 'error');
  2911. }
  2912. } catch (err) {
  2913. showToast('Error', err.message, 'error');
  2914. }
  2915. }
  2916. async function toggleAddrListState(id, disabled) {
  2917. try {
  2918. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
  2919. method: 'POST',
  2920. headers: { 'Content-Type': 'application/json' },
  2921. body: JSON.stringify({ disabled })
  2922. });
  2923. if (res.ok) {
  2924. loadFirewall(false);
  2925. }
  2926. } catch (err) {
  2927. showToast('Error', err.message, 'error');
  2928. }
  2929. }
  2930. async function deleteAddrList(id) {
  2931. if (!confirm('Are you sure you want to delete this address list item?')) return;
  2932. try {
  2933. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  2934. if (res.ok) {
  2935. showToast('Deleted', 'Address list item removed', 'info');
  2936. loadFirewall(false);
  2937. }
  2938. } catch (err) {
  2939. showToast('Error', err.message, 'error');
  2940. }
  2941. }
  2942. // ----------------- Geo-Location IP Management -----------------
  2943. async function loadGeoIP() {
  2944. try {
  2945. const [statusRes, countriesRes] = await Promise.all([
  2946. fetch(`${API_BASE}/firewall/geoip/status`),
  2947. fetch(`${API_BASE}/firewall/geoip/countries`)
  2948. ]);
  2949. if (statusRes.ok) state.geoStatus = await statusRes.json();
  2950. if (countriesRes.ok) state.geoCountries = await countriesRes.json();
  2951. updateGeoHeader();
  2952. renderGeoCountries();
  2953. } catch (err) {
  2954. console.error('Failed to load GeoIP:', err);
  2955. }
  2956. }
  2957. function getGeoUsageMap() {
  2958. const usage = {};
  2959. const checkRule = (r, type) => {
  2960. ['src_geoip', 'dst_geoip'].forEach(field => {
  2961. let val = (r && r[field]) || '';
  2962. let code = val.replace(/^!/, '').replace(/^geo:/, '').replace(/^geo_/, '').toUpperCase().trim();
  2963. if (code) {
  2964. if (!usage[code]) usage[code] = [];
  2965. const label = `${type} #${r.priority !== undefined ? r.priority : (r.id || '')}`;
  2966. if (!usage[code].includes(label)) usage[code].push(label);
  2967. }
  2968. });
  2969. };
  2970. (state.filterRules || []).forEach(r => checkRule(r, 'Filter'));
  2971. (state.natRules || []).forEach(r => checkRule(r, 'NAT'));
  2972. (state.mangleRules || []).forEach(r => checkRule(r, 'Mangle'));
  2973. return usage;
  2974. }
  2975. function updateGeoHeader() {
  2976. const s = state.geoStatus || {};
  2977. const statusBadge = document.getElementById('geo-status-badge');
  2978. if (statusBadge) {
  2979. statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
  2980. statusBadge.className = s.auto_update
  2981. ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
  2982. : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
  2983. }
  2984. const intervalLabel = document.getElementById('geo-interval-label');
  2985. if (intervalLabel) {
  2986. intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
  2987. }
  2988. const usageMap = getGeoUsageMap();
  2989. const inUseCount = Object.keys(usageMap).length;
  2990. const activeCountEl = document.getElementById('geo-stat-active-countries');
  2991. if (activeCountEl) activeCountEl.innerText = inUseCount.toLocaleString();
  2992. const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
  2993. if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
  2994. const lastSyncEl = document.getElementById('geo-stat-last-sync');
  2995. if (lastSyncEl) {
  2996. if (s.last_updated && !s.last_updated.startsWith('0001')) {
  2997. const d = new Date(s.last_updated);
  2998. lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  2999. } else {
  3000. lastSyncEl.innerText = 'Never (Sync Pending)';
  3001. }
  3002. }
  3003. const nextSyncEl = document.getElementById('geo-stat-next-sync');
  3004. if (nextSyncEl) {
  3005. if (s.next_update && !s.next_update.startsWith('0001')) {
  3006. const d = new Date(s.next_update);
  3007. nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  3008. } else {
  3009. nextSyncEl.innerText = '-';
  3010. }
  3011. }
  3012. const badge = document.getElementById('fw-badge-geo');
  3013. if (badge) badge.innerText = inUseCount || (state.geoCountries || []).filter(c => c.subnet_count > 0).length || 0;
  3014. }
  3015. function renderGeoCountries() {
  3016. const tbody = document.getElementById('geo-table-body');
  3017. const empty = document.getElementById('geo-empty');
  3018. if (!tbody) return;
  3019. tbody.innerHTML = '';
  3020. const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
  3021. const continent = document.getElementById('geo-continent-filter')?.value || '';
  3022. const inUseOnly = document.getElementById('geo-filter-inuse-only')?.checked;
  3023. const cachedOnly = document.getElementById('geo-filter-cached-only')?.checked;
  3024. const usageMap = getGeoUsageMap();
  3025. const countries = (state.geoCountries || []).filter(c => {
  3026. const isUsed = !!usageMap[c.code];
  3027. if (inUseOnly && !isUsed) return false;
  3028. if (cachedOnly && (!c.subnet_count || c.subnet_count === 0)) return false;
  3029. if (continent && c.continent !== continent) return false;
  3030. if (q) {
  3031. const matchCode = c.code.toLowerCase().includes(q);
  3032. const matchName = c.name.toLowerCase().includes(q);
  3033. if (!matchCode && !matchName) return false;
  3034. }
  3035. return true;
  3036. });
  3037. if (countries.length === 0) {
  3038. empty?.classList.remove('hidden');
  3039. return;
  3040. }
  3041. empty?.classList.add('hidden');
  3042. countries.forEach(c => {
  3043. const tr = document.createElement('tr');
  3044. const isUsed = !!usageMap[c.code];
  3045. const rulesUsing = usageMap[c.code] || [];
  3046. tr.className = `hover:bg-slate-800/40 transition text-xs ${isUsed ? 'bg-emerald-950/20' : ''}`;
  3047. let statusHtml = '';
  3048. if (isUsed) {
  3049. 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>`;
  3050. } else if (c.subnet_count > 0) {
  3051. 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>';
  3052. } else {
  3053. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-slate-500 bg-slate-800/60">READY</span>';
  3054. }
  3055. tr.innerHTML = `
  3056. <td class="py-2.5 px-3 text-center">
  3057. <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'}">
  3058. ${c.code}
  3059. </span>
  3060. </td>
  3061. <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
  3062. <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
  3063. <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
  3064. ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
  3065. </td>
  3066. <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
  3067. <td class="py-2.5 px-3">
  3068. ${statusHtml}
  3069. </td>
  3070. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  3071. <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>
  3072. <button onclick="viewGeoSubnets('${c.code}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
  3073. </td>
  3074. `;
  3075. tbody.appendChild(tr);
  3076. });
  3077. }
  3078. function quickFilterGeo(preset) {
  3079. const searchInput = document.getElementById('geo-search-input');
  3080. const continentSel = document.getElementById('geo-continent-filter');
  3081. const inUseCheck = document.getElementById('geo-filter-inuse-only');
  3082. const cachedCheck = document.getElementById('geo-filter-cached-only');
  3083. if (searchInput) searchInput.value = '';
  3084. if (continentSel) continentSel.value = '';
  3085. if (inUseCheck) inUseCheck.checked = false;
  3086. if (cachedCheck) cachedCheck.checked = false;
  3087. if (preset === 'GR') {
  3088. if (searchInput) searchInput.value = 'Greece';
  3089. } else if (preset === 'Europe') {
  3090. if (continentSel) continentSel.value = 'Europe';
  3091. } else if (preset === 'HIGHRISK') {
  3092. if (searchInput) searchInput.value = 'China';
  3093. }
  3094. renderGeoCountries();
  3095. }
  3096. async function toggleGeoCountry(code, enabled) {
  3097. try {
  3098. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
  3099. method: 'POST',
  3100. headers: { 'Content-Type': 'application/json' },
  3101. body: JSON.stringify({ enabled })
  3102. });
  3103. if (res.ok) {
  3104. showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
  3105. loadGeoIP();
  3106. } else {
  3107. const err = await res.json();
  3108. showToast('Error', err.message || 'Failed to toggle country', 'error');
  3109. }
  3110. } catch (err) {
  3111. showToast('Error', err.message, 'error');
  3112. }
  3113. }
  3114. async function updateGeoCountry(code) {
  3115. try {
  3116. showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
  3117. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
  3118. if (res.ok) {
  3119. const data = await res.json();
  3120. showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
  3121. loadGeoIP();
  3122. } else {
  3123. const err = await res.json();
  3124. showToast('Sync Error', err.message || 'Failed to sync country', 'error');
  3125. }
  3126. } catch (err) {
  3127. showToast('Error', err.message, 'error');
  3128. }
  3129. }
  3130. async function triggerGeoUpdateNow() {
  3131. const spinner = document.getElementById('geo-update-spinner');
  3132. if (spinner) spinner.classList.remove('hidden');
  3133. try {
  3134. const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
  3135. if (res.ok) {
  3136. showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
  3137. setTimeout(() => {
  3138. loadGeoIP();
  3139. if (spinner) spinner.classList.add('hidden');
  3140. }, 2500);
  3141. } else {
  3142. const err = await res.json();
  3143. showToast('Notice', err.message || 'Update in progress', 'info');
  3144. if (spinner) spinner.classList.add('hidden');
  3145. }
  3146. } catch (err) {
  3147. showToast('Error', err.message, 'error');
  3148. if (spinner) spinner.classList.add('hidden');
  3149. }
  3150. }
  3151. async function applyGeoPreset(preset) {
  3152. try {
  3153. const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
  3154. method: 'POST',
  3155. headers: { 'Content-Type': 'application/json' },
  3156. body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
  3157. });
  3158. if (res.ok) {
  3159. showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
  3160. loadGeoIP();
  3161. }
  3162. } catch (err) {
  3163. showToast('Error', err.message, 'error');
  3164. }
  3165. }
  3166. function openGeoIntervalModal() {
  3167. const s = state.geoStatus || {};
  3168. document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
  3169. const sel = document.getElementById('geo-cfg-interval');
  3170. const customBox = document.getElementById('geo-cfg-custom-box');
  3171. const customHoursInput = document.getElementById('geo-cfg-custom-hours');
  3172. const curHours = s.interval_hours || 24;
  3173. const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
  3174. if (matchOption) {
  3175. sel.value = String(curHours);
  3176. customBox.classList.add('hidden');
  3177. } else {
  3178. sel.value = 'custom';
  3179. customHoursInput.value = curHours;
  3180. customBox.classList.remove('hidden');
  3181. }
  3182. document.getElementById('geo-interval-modal').classList.remove('hidden');
  3183. }
  3184. function closeGeoIntervalModal() {
  3185. document.getElementById('geo-interval-modal').classList.add('hidden');
  3186. }
  3187. function toggleCustomGeoInterval() {
  3188. const val = document.getElementById('geo-cfg-interval').value;
  3189. const customBox = document.getElementById('geo-cfg-custom-box');
  3190. if (val === 'custom') {
  3191. customBox.classList.remove('hidden');
  3192. } else {
  3193. customBox.classList.add('hidden');
  3194. }
  3195. }
  3196. async function submitGeoIntervalSettings(e) {
  3197. e.preventDefault();
  3198. const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
  3199. const intervalVal = document.getElementById('geo-cfg-interval').value;
  3200. let hours = 24;
  3201. if (intervalVal === 'custom') {
  3202. hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
  3203. } else {
  3204. hours = parseInt(intervalVal, 10) || 24;
  3205. }
  3206. try {
  3207. const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
  3208. method: 'POST',
  3209. headers: { 'Content-Type': 'application/json' },
  3210. body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
  3211. });
  3212. if (res.ok) {
  3213. showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
  3214. closeGeoIntervalModal();
  3215. loadGeoIP();
  3216. } else {
  3217. const err = await res.json();
  3218. showToast('Error', err.message || 'Failed to save schedule', 'error');
  3219. }
  3220. } catch (err) {
  3221. showToast('Error', err.message, 'error');
  3222. }
  3223. }
  3224. async function viewGeoSubnets(code, name) {
  3225. if (!name) {
  3226. const found = (state.geoCountries || []).find(x => x.code === code);
  3227. name = found ? found.name : code;
  3228. }
  3229. document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
  3230. document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
  3231. const listEl = document.getElementById('geo-subnets-list');
  3232. listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
  3233. document.getElementById('geo-subnets-modal').classList.remove('hidden');
  3234. try {
  3235. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
  3236. if (res.ok) {
  3237. const data = await res.json();
  3238. const subnets = data.subnets || [];
  3239. if (subnets.length === 0) {
  3240. listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
  3241. } else {
  3242. listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
  3243. }
  3244. } else {
  3245. listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
  3246. }
  3247. } catch (err) {
  3248. listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
  3249. }
  3250. }
  3251. function closeGeoSubnetsModal() {
  3252. document.getElementById('geo-subnets-modal').classList.add('hidden');
  3253. }
  3254. // ----------------- Active Connections Tracking -----------------
  3255. async function loadConnections() {
  3256. try {
  3257. const res = await fetch(`${API_BASE}/firewall/connections`);
  3258. const data = await res.json();
  3259. state.connections = Array.isArray(data) ? data : [];
  3260. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  3261. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  3262. renderConnections();
  3263. } catch (err) {
  3264. console.error('Failed to load connections:', err);
  3265. }
  3266. }
  3267. function renderConnections() {
  3268. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  3269. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  3270. const tbody = document.getElementById('conns-table-body');
  3271. const empty = document.getElementById('conns-empty');
  3272. if (!tbody) return;
  3273. tbody.innerHTML = '';
  3274. const conns = (state.connections || []).filter(c => {
  3275. if (protoFilter && c.protocol !== protoFilter) return false;
  3276. if (search) {
  3277. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  3278. if (!line.includes(search)) return false;
  3279. }
  3280. return true;
  3281. });
  3282. if (conns.length === 0) {
  3283. empty?.classList.remove('hidden');
  3284. return;
  3285. }
  3286. empty?.classList.add('hidden');
  3287. conns.slice(0, 150).forEach(c => {
  3288. const tr = document.createElement('tr');
  3289. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  3290. let stateColor = 'text-slate-400';
  3291. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  3292. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  3293. tr.innerHTML = `
  3294. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  3295. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  3296. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  3297. <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>
  3298. <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>
  3299. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  3300. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  3301. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  3302. <td class="py-2.5 px-3 text-right font-sans">
  3303. <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>
  3304. </td>
  3305. `;
  3306. tbody.appendChild(tr);
  3307. });
  3308. }
  3309. async function killConnection(protocol, src, sport, dst, dport) {
  3310. try {
  3311. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  3312. method: 'POST',
  3313. headers: { 'Content-Type': 'application/json' },
  3314. body: JSON.stringify({ protocol, src, sport, dst, dport })
  3315. });
  3316. if (res.ok) {
  3317. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  3318. loadConnections();
  3319. }
  3320. } catch (err) {
  3321. showToast('Error', err.message, 'error');
  3322. }
  3323. }
  3324. async function resetFirewallCounters() {
  3325. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  3326. try {
  3327. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  3328. if (res.ok) {
  3329. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  3330. loadFirewall(false);
  3331. }
  3332. } catch (err) {
  3333. showToast('Error', err.message, 'error');
  3334. }
  3335. }
  3336. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  3337. function switchRoutesSubTab(tab) {
  3338. state.routesSubTab = tab;
  3339. const tabs = ['routes', 'rules', 'tables'];
  3340. tabs.forEach(t => {
  3341. const panel = document.getElementById(`routes-subtab-${t}`);
  3342. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  3343. if (panel) {
  3344. if (t === tab) panel.classList.remove('hidden');
  3345. else panel.classList.add('hidden');
  3346. }
  3347. if (btn) {
  3348. if (t === tab) {
  3349. 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';
  3350. } else {
  3351. 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';
  3352. }
  3353. }
  3354. });
  3355. }
  3356. async function loadRoutes() {
  3357. try {
  3358. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  3359. fetch(`${API_BASE}/routes`),
  3360. fetch(`${API_BASE}/routing/rules`),
  3361. fetch(`${API_BASE}/routing/tables`)
  3362. ]);
  3363. if (routesRes.ok) state.routes = await routesRes.json();
  3364. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  3365. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  3366. const bRoutes = document.getElementById('routes-badge-routes');
  3367. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  3368. const bRules = document.getElementById('routes-badge-rules');
  3369. if (bRules) bRules.innerText = (state.policyRules || []).length;
  3370. const bTables = document.getElementById('routes-badge-tables');
  3371. if (bTables) bTables.innerText = (state.routingTables || []).length;
  3372. const bRoutesCount = document.getElementById('badge-routes-count');
  3373. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  3374. renderRoutesList();
  3375. renderPolicyRules();
  3376. renderRoutingTables();
  3377. } catch (err) {
  3378. console.error('Failed to load routing:', err);
  3379. }
  3380. }
  3381. function renderRoutesList() {
  3382. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  3383. const tbody = document.getElementById('routes-table-body');
  3384. const empty = document.getElementById('routes-empty');
  3385. if (!tbody) return;
  3386. tbody.innerHTML = '';
  3387. // Update table filter select
  3388. const sel = document.getElementById('routes-filter-table');
  3389. if (sel) {
  3390. const cur = sel.value;
  3391. sel.innerHTML = '<option value="">All Tables</option>';
  3392. (state.routingTables || []).forEach(t => {
  3393. const opt = document.createElement('option');
  3394. opt.value = t.name;
  3395. opt.innerText = t.name;
  3396. if (t.name === cur) opt.selected = true;
  3397. sel.appendChild(opt);
  3398. });
  3399. }
  3400. const routes = (state.routes || []).filter(r => !tableFilter || r.routing_table === tableFilter);
  3401. document.getElementById('routes-count-badge').innerText = `${routes.length} Routes`;
  3402. if (routes.length === 0) {
  3403. empty?.classList.remove('hidden');
  3404. return;
  3405. }
  3406. empty?.classList.add('hidden');
  3407. routes.forEach(r => {
  3408. const tr = document.createElement('tr');
  3409. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  3410. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  3411. // MikroTik Flags string: D=Dynamic, A=Active, C=Connect, S=Static, X=Disabled
  3412. let flags = '';
  3413. if (r.dynamic) flags += 'D';
  3414. if (r.active) flags += 'A';
  3415. if (r.connect) flags += 'C';
  3416. if (r.static) flags += 'S';
  3417. if (r.disabled) flags += 'X';
  3418. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  3419. tr.innerHTML = `
  3420. <td class="py-2.5 px-3 text-center">
  3421. <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'}">
  3422. ${flags || '-'}
  3423. </span>
  3424. </td>
  3425. <td class="py-2.5 px-3 font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${r.dst_address}</td>
  3426. <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>
  3427. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  3428. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  3429. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  3430. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  3431. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  3432. ${r.static ? `
  3433. <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>
  3434. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  3435. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3436. ` : `
  3437. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  3438. `}
  3439. </td>
  3440. `;
  3441. tbody.appendChild(tr);
  3442. });
  3443. }
  3444. function openAddRouteModal() {
  3445. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  3446. document.getElementById('route-modal-id').value = '';
  3447. document.getElementById('route-modal-old-dst').value = '';
  3448. document.getElementById('route-modal-old-gw').value = '';
  3449. document.getElementById('route-modal-old-distance').value = '';
  3450. document.getElementById('route-modal-old-table').value = '';
  3451. document.getElementById('route-modal-old-iface').value = '';
  3452. const dstInput = document.getElementById('route-modal-dst');
  3453. const gwInput = document.getElementById('route-modal-gw');
  3454. const distInput = document.getElementById('route-modal-distance');
  3455. const ifaceSelect = document.getElementById('route-modal-iface');
  3456. const tableSelect = document.getElementById('route-modal-table');
  3457. const commentInput = document.getElementById('route-modal-comment');
  3458. const disCheck = document.getElementById('route-modal-disabled');
  3459. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  3460. dstInput.disabled = false;
  3461. dstInput.value = '0.0.0.0/0';
  3462. gwInput.disabled = false;
  3463. gwInput.value = '';
  3464. distInput.disabled = false;
  3465. distInput.value = '1';
  3466. ifaceSelect.disabled = false;
  3467. tableSelect.disabled = false;
  3468. commentInput.disabled = false;
  3469. commentInput.value = '';
  3470. disCheck.disabled = false;
  3471. disCheck.checked = false;
  3472. if (saveBtn) saveBtn.classList.remove('hidden');
  3473. populateInterfaceSelect('route-modal-iface');
  3474. // Populate tables
  3475. tableSelect.innerHTML = '';
  3476. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  3477. const opt = document.createElement('option');
  3478. opt.value = t.name;
  3479. opt.innerText = t.name;
  3480. if (t.name === 'main') opt.selected = true;
  3481. tableSelect.appendChild(opt);
  3482. });
  3483. document.getElementById('route-modal').classList.remove('hidden');
  3484. }
  3485. function openEditRouteModal(id) {
  3486. const r = (state.routes || []).find(route => route.id === id);
  3487. if (!r) return;
  3488. const isStatic = !!r.static;
  3489. document.getElementById('route-modal-title').innerText = isStatic
  3490. ? `Edit Route: ${r.dst_address}`
  3491. : `Route Properties (Read Only): ${r.dst_address}`;
  3492. document.getElementById('route-modal-id').value = r.id;
  3493. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  3494. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  3495. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  3496. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  3497. document.getElementById('route-modal-old-iface').value = r.interface || '';
  3498. const dstInput = document.getElementById('route-modal-dst');
  3499. const gwInput = document.getElementById('route-modal-gw');
  3500. const distInput = document.getElementById('route-modal-distance');
  3501. const ifaceSelect = document.getElementById('route-modal-iface');
  3502. const tableSelect = document.getElementById('route-modal-table');
  3503. const commentInput = document.getElementById('route-modal-comment');
  3504. const disCheck = document.getElementById('route-modal-disabled');
  3505. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  3506. dstInput.value = r.dst_address;
  3507. gwInput.value = r.gateway || '';
  3508. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  3509. commentInput.value = r.comment || '';
  3510. disCheck.checked = !!r.disabled;
  3511. dstInput.disabled = !isStatic;
  3512. gwInput.disabled = !isStatic;
  3513. distInput.disabled = !isStatic;
  3514. ifaceSelect.disabled = !isStatic;
  3515. tableSelect.disabled = !isStatic;
  3516. commentInput.disabled = !isStatic;
  3517. disCheck.disabled = !isStatic;
  3518. if (saveBtn) {
  3519. if (isStatic) {
  3520. saveBtn.classList.remove('hidden');
  3521. } else {
  3522. saveBtn.classList.add('hidden');
  3523. }
  3524. }
  3525. populateInterfaceSelect('route-modal-iface', r.interface);
  3526. tableSelect.innerHTML = '';
  3527. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  3528. const opt = document.createElement('option');
  3529. opt.value = t.name;
  3530. opt.innerText = t.name;
  3531. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  3532. tableSelect.appendChild(opt);
  3533. });
  3534. document.getElementById('route-modal').classList.remove('hidden');
  3535. }
  3536. function closeRouteModal() {
  3537. document.getElementById('route-modal').classList.add('hidden');
  3538. }
  3539. async function submitSaveRoute(e) {
  3540. e.preventDefault();
  3541. const id = document.getElementById('route-modal-id').value;
  3542. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  3543. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  3544. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  3545. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  3546. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  3547. const dst = document.getElementById('route-modal-dst').value.trim();
  3548. const gw = document.getElementById('route-modal-gw').value.trim();
  3549. const table = document.getElementById('route-modal-table').value;
  3550. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  3551. const iface = document.getElementById('route-modal-iface').value;
  3552. const comment = document.getElementById('route-modal-comment').value.trim();
  3553. const disabled = document.getElementById('route-modal-disabled').checked;
  3554. if (!dst) {
  3555. showToast('Error', 'Destination address is required', 'error');
  3556. return;
  3557. }
  3558. if (!gw && !iface) {
  3559. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  3560. return;
  3561. }
  3562. const payload = {
  3563. id,
  3564. old_dst_address: oldDst,
  3565. old_gateway: oldGw,
  3566. old_routing_table: oldTable,
  3567. old_interface: oldIface,
  3568. dst_address: dst,
  3569. gateway: gw || iface,
  3570. routing_table: table,
  3571. distance,
  3572. interface: iface,
  3573. comment,
  3574. disabled
  3575. };
  3576. if (oldDistStr !== undefined && oldDistStr !== '') {
  3577. payload.old_distance = parseInt(oldDistStr, 10);
  3578. }
  3579. try {
  3580. const res = await fetch(`${API_BASE}/routes`, {
  3581. method: 'POST',
  3582. headers: { 'Content-Type': 'application/json' },
  3583. body: JSON.stringify(payload)
  3584. });
  3585. if (res.ok) {
  3586. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  3587. closeRouteModal();
  3588. loadRoutes();
  3589. } else {
  3590. const err = await res.json();
  3591. showToast('Error', err.message || 'Failed to save route', 'error');
  3592. }
  3593. } catch (err) {
  3594. showToast('Error', err.message, 'error');
  3595. }
  3596. }
  3597. async function toggleRouteState(id, disabled) {
  3598. try {
  3599. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  3600. method: 'POST',
  3601. headers: { 'Content-Type': 'application/json' },
  3602. body: JSON.stringify({ disabled })
  3603. });
  3604. if (res.ok) loadRoutes();
  3605. } catch (err) {
  3606. showToast('Error', err.message, 'error');
  3607. }
  3608. }
  3609. async function deleteRoute(id) {
  3610. if (!confirm('Are you sure you want to delete this route?')) return;
  3611. try {
  3612. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3613. if (res.ok) {
  3614. showToast('Deleted', 'Route removed', 'success');
  3615. loadRoutes();
  3616. }
  3617. } catch (err) {
  3618. showToast('Error', err.message, 'error');
  3619. }
  3620. }
  3621. // ----------------- Policy Rules (/ip route rule) -----------------
  3622. function renderPolicyRules() {
  3623. const tbody = document.getElementById('rules-table-body');
  3624. const empty = document.getElementById('rules-empty');
  3625. if (!tbody) return;
  3626. tbody.innerHTML = '';
  3627. const rules = state.policyRules || [];
  3628. document.getElementById('rules-count-badge').innerText = `${rules.length} Rules`;
  3629. if (rules.length === 0) {
  3630. empty?.classList.remove('hidden');
  3631. return;
  3632. }
  3633. empty?.classList.add('hidden');
  3634. rules.forEach(pr => {
  3635. const tr = document.createElement('tr');
  3636. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  3637. tr.innerHTML = `
  3638. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  3639. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  3640. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  3641. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  3642. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  3643. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  3644. <td class="py-2.5 px-3 text-right font-sans">
  3645. ${pr.priority < 32766 && pr.priority > 0 ? `
  3646. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3647. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  3648. </td>
  3649. `;
  3650. tbody.appendChild(tr);
  3651. });
  3652. }
  3653. function openAddPolicyRuleModal() {
  3654. document.getElementById('prule-modal-pref').value = (state.policyRules || []).length * 10 + 1000;
  3655. document.getElementById('prule-modal-mark').value = '';
  3656. document.getElementById('prule-modal-src').value = '';
  3657. document.getElementById('prule-modal-dst').value = '';
  3658. const sel = document.getElementById('prule-modal-table');
  3659. sel.innerHTML = '';
  3660. (state.routingTables || []).forEach(t => {
  3661. const opt = document.createElement('option');
  3662. opt.value = t.name;
  3663. opt.innerText = t.name;
  3664. sel.appendChild(opt);
  3665. });
  3666. document.getElementById('prule-modal').classList.remove('hidden');
  3667. }
  3668. function closePolicyRuleModal() {
  3669. document.getElementById('prule-modal').classList.add('hidden');
  3670. }
  3671. async function submitSavePolicyRule(e) {
  3672. e.preventDefault();
  3673. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  3674. const mark = document.getElementById('prule-modal-mark').value.trim();
  3675. const src = document.getElementById('prule-modal-src').value.trim();
  3676. const dst = document.getElementById('prule-modal-dst').value.trim();
  3677. const table = document.getElementById('prule-modal-table').value;
  3678. const action = document.getElementById('prule-modal-action').value;
  3679. try {
  3680. const res = await fetch(`${API_BASE}/routing/rules`, {
  3681. method: 'POST',
  3682. headers: { 'Content-Type': 'application/json' },
  3683. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  3684. });
  3685. if (res.ok) {
  3686. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  3687. closePolicyRuleModal();
  3688. loadRoutes();
  3689. } else {
  3690. const err = await res.json();
  3691. showToast('Error', err.message, 'error');
  3692. }
  3693. } catch (err) {
  3694. showToast('Error', err.message, 'error');
  3695. }
  3696. }
  3697. async function deletePolicyRule(id) {
  3698. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  3699. try {
  3700. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3701. if (res.ok) {
  3702. showToast('Rule Removed', 'Policy rule deleted', 'success');
  3703. loadRoutes();
  3704. }
  3705. } catch (err) {
  3706. showToast('Error', err.message, 'error');
  3707. }
  3708. }
  3709. // ----------------- Routing Tables -----------------
  3710. function renderRoutingTables() {
  3711. const tbody = document.getElementById('tables-table-body');
  3712. if (!tbody) return;
  3713. tbody.innerHTML = '';
  3714. (state.routingTables || []).forEach(t => {
  3715. const tr = document.createElement('tr');
  3716. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  3717. tr.innerHTML = `
  3718. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  3719. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  3720. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  3721. `;
  3722. tbody.appendChild(tr);
  3723. });
  3724. }
  3725. function openAddTableModal() {
  3726. document.getElementById('table-modal-name').value = '';
  3727. document.getElementById('table-modal-id').value = '';
  3728. document.getElementById('table-modal-comment').value = '';
  3729. document.getElementById('table-modal').classList.remove('hidden');
  3730. }
  3731. function closeTableModal() {
  3732. document.getElementById('table-modal').classList.add('hidden');
  3733. }
  3734. async function submitSaveTable(e) {
  3735. e.preventDefault();
  3736. const name = document.getElementById('table-modal-name').value.trim();
  3737. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  3738. const comment = document.getElementById('table-modal-comment').value.trim();
  3739. try {
  3740. const res = await fetch(`${API_BASE}/routing/tables`, {
  3741. method: 'POST',
  3742. headers: { 'Content-Type': 'application/json' },
  3743. body: JSON.stringify({ name, table_id: id, comment })
  3744. });
  3745. if (res.ok) {
  3746. showToast('Table Created', `Routing table ${name} registered`, 'success');
  3747. closeTableModal();
  3748. loadRoutes();
  3749. } else {
  3750. const err = await res.json();
  3751. showToast('Error', err.message, 'error');
  3752. }
  3753. } catch (err) {
  3754. showToast('Error', err.message, 'error');
  3755. }
  3756. }
  3757. async function loadDebianConfig() {
  3758. const view = document.getElementById('debian-config-view');
  3759. view.innerText = 'Generating live configuration...';
  3760. try {
  3761. const res = await fetch(`${API_BASE}/debian/config`);
  3762. const data = await res.json();
  3763. view.innerText = data.content || '# Empty config';
  3764. } catch (err) {
  3765. view.innerText = 'Failed to generate Debian network config.';
  3766. }
  3767. }
  3768. async function saveDebianConfig() {
  3769. try {
  3770. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  3771. const data = await res.json();
  3772. if (res.ok) {
  3773. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  3774. loadDebianConfig();
  3775. }
  3776. } catch (err) {
  3777. showToast('Error', err.message, 'error');
  3778. }
  3779. }
  3780. function showToast(title, message, type = 'info') {
  3781. const container = document.getElementById('toast-container');
  3782. const toast = document.createElement('div');
  3783. const borderColors = {
  3784. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  3785. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  3786. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  3787. };
  3788. 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}`;
  3789. toast.innerHTML = `
  3790. <div class="flex-1">
  3791. <div class="font-bold text-xs text-white">${title}</div>
  3792. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${message}</div>
  3793. </div>
  3794. `;
  3795. container.appendChild(toast);
  3796. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  3797. setTimeout(() => {
  3798. toast.classList.add('opacity-0', 'translate-y-2');
  3799. setTimeout(() => toast.remove(), 300);
  3800. }, 4000);
  3801. }
  3802. function formatTraffic(bytesPerSec) {
  3803. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  3804. const kb = bytesPerSec / 1024;
  3805. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  3806. const mb = kb / 1024;
  3807. return `${mb.toFixed(2)} MB/s`;
  3808. }
  3809. function toggleSidebar() {
  3810. const sb = document.getElementById('sidebar');
  3811. sb.classList.toggle('-translate-x-full');
  3812. }
  3813. // ======================== EoIP (Ethernet over IP) ========================
  3814. async function loadEoIP(populate = true) {
  3815. try {
  3816. const res = await fetch(`${API_BASE}/vpn/eoip`);
  3817. const data = await res.json();
  3818. state.eoipTunnels = Array.isArray(data) ? data : [];
  3819. const badge = document.getElementById('eoip-count-badge');
  3820. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  3821. const sideBadge = document.getElementById('badge-eoip-count');
  3822. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  3823. renderEoIPTunnels();
  3824. } catch (err) {
  3825. console.error('Failed to load EoIP:', err);
  3826. }
  3827. }
  3828. function renderEoIPTunnels() {
  3829. const tbody = document.getElementById('eoip-table-body');
  3830. const empty = document.getElementById('eoip-empty');
  3831. if (!tbody) return;
  3832. tbody.innerHTML = '';
  3833. const tunnels = state.eoipTunnels || [];
  3834. if (tunnels.length === 0) {
  3835. empty?.classList.remove('hidden');
  3836. return;
  3837. }
  3838. empty?.classList.add('hidden');
  3839. tunnels.forEach(t => {
  3840. const tr = document.createElement('tr');
  3841. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  3842. tr.innerHTML = `
  3843. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  3844. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  3845. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  3846. <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>
  3847. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  3848. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  3849. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  3850. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  3851. <td class="py-2.5 px-3 font-mono text-[11px]">
  3852. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  3853. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  3854. </td>
  3855. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  3856. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3857. <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>
  3858. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3859. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  3860. </td>
  3861. `;
  3862. tbody.appendChild(tr);
  3863. });
  3864. }
  3865. function openAddEoIPModal() {
  3866. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  3867. document.getElementById('eoip-modal-id').value = '';
  3868. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  3869. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  3870. document.getElementById('eoip-modal-remote').value = '';
  3871. document.getElementById('eoip-modal-ip').value = '';
  3872. document.getElementById('eoip-modal-local').value = '';
  3873. document.getElementById('eoip-modal-mac').value = '';
  3874. document.getElementById('eoip-modal-mtu').value = '1500';
  3875. document.getElementById('eoip-modal-comment').value = '';
  3876. document.getElementById('eoip-modal-clampmss').checked = true;
  3877. document.getElementById('eoip-modal-disabled').checked = false;
  3878. document.getElementById('eoip-modal').classList.remove('hidden');
  3879. }
  3880. function openEditEoIPModal(id) {
  3881. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  3882. if (!t) return;
  3883. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  3884. document.getElementById('eoip-modal-id').value = t.id;
  3885. document.getElementById('eoip-modal-name').value = t.name;
  3886. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  3887. document.getElementById('eoip-modal-remote').value = t.remote_address;
  3888. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  3889. document.getElementById('eoip-modal-local').value = t.local_address || '';
  3890. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  3891. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  3892. document.getElementById('eoip-modal-comment').value = t.comment || '';
  3893. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  3894. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  3895. document.getElementById('eoip-modal').classList.remove('hidden');
  3896. }
  3897. function closeEoIPModal() {
  3898. document.getElementById('eoip-modal').classList.add('hidden');
  3899. }
  3900. async function submitSaveEoIP(e) {
  3901. e.preventDefault();
  3902. const id = document.getElementById('eoip-modal-id').value;
  3903. const name = document.getElementById('eoip-modal-name').value.trim();
  3904. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  3905. const remote = document.getElementById('eoip-modal-remote').value.trim();
  3906. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  3907. const local = document.getElementById('eoip-modal-local').value.trim();
  3908. const mac = document.getElementById('eoip-modal-mac').value.trim();
  3909. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  3910. const comment = document.getElementById('eoip-modal-comment').value.trim();
  3911. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  3912. const disabled = document.getElementById('eoip-modal-disabled').checked;
  3913. try {
  3914. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  3915. method: 'POST',
  3916. headers: { 'Content-Type': 'application/json' },
  3917. body: JSON.stringify({
  3918. id,
  3919. name,
  3920. tunnel_id: tunnelId,
  3921. remote_address: remote,
  3922. ip_address: ipAddress,
  3923. local_address: local,
  3924. mac_address: mac,
  3925. mtu,
  3926. clamp_mss: clampMss,
  3927. comment,
  3928. disabled
  3929. })
  3930. });
  3931. if (res.ok) {
  3932. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  3933. closeEoIPModal();
  3934. loadEoIP(false);
  3935. fetchData(false);
  3936. } else {
  3937. const err = await res.json();
  3938. showToast('Error', err.message, 'error');
  3939. }
  3940. } catch (err) {
  3941. showToast('Error', err.message, 'error');
  3942. }
  3943. }
  3944. async function toggleEoIPState(id, disabled) {
  3945. try {
  3946. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  3947. method: 'POST',
  3948. headers: { 'Content-Type': 'application/json' },
  3949. body: JSON.stringify({ disabled })
  3950. });
  3951. if (res.ok) {
  3952. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  3953. loadEoIP(false);
  3954. fetchData(false);
  3955. }
  3956. } catch (err) {
  3957. showToast('Error', err.message, 'error');
  3958. }
  3959. }
  3960. async function deleteEoIP(id) {
  3961. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  3962. try {
  3963. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3964. if (res.ok) {
  3965. showToast('Deleted', 'EoIP tunnel removed', 'success');
  3966. loadEoIP(false);
  3967. fetchData(false);
  3968. }
  3969. } catch (err) {
  3970. showToast('Error', err.message, 'error');
  3971. }
  3972. }
  3973. // ======================== PPP Central Hub & Servers ========================
  3974. function switchPPPSubTab(tab) {
  3975. state.pppSubTab = tab;
  3976. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  3977. tabs.forEach(t => {
  3978. const panel = document.getElementById(`ppp-subtab-${t}`);
  3979. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  3980. if (panel) {
  3981. if (t === tab) panel.classList.remove('hidden');
  3982. else panel.classList.add('hidden');
  3983. }
  3984. if (btn) {
  3985. if (t === tab) {
  3986. 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';
  3987. } else {
  3988. 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';
  3989. }
  3990. }
  3991. });
  3992. const addBtn = document.getElementById('ppp-primary-add-btn');
  3993. if (addBtn) {
  3994. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  3995. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  3996. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  3997. else addBtn.innerHTML = '<span>Save Config</span>';
  3998. }
  3999. if (tab === 'active') loadPPPSessions();
  4000. }
  4001. function openCurrentPPPModal() {
  4002. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  4003. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  4004. else if (state.pppSubTab === 'active') loadPPPSessions();
  4005. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  4006. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  4007. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  4008. }
  4009. async function loadPPP(populateDropdowns = true) {
  4010. await Promise.all([
  4011. loadPPPSecrets(),
  4012. loadPPPProfiles(),
  4013. loadPPPServers(),
  4014. loadPPPSessions()
  4015. ]);
  4016. }
  4017. async function loadPPPSecrets() {
  4018. try {
  4019. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  4020. const data = await res.json();
  4021. state.pppSecrets = Array.isArray(data) ? data : [];
  4022. const b = document.getElementById('ppp-badge-secrets');
  4023. if (b) b.innerText = state.pppSecrets.length;
  4024. const b2 = document.getElementById('secrets-count-badge');
  4025. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  4026. renderPPPSecrets();
  4027. } catch (err) {
  4028. console.error('Failed to load PPP secrets:', err);
  4029. }
  4030. }
  4031. function renderPPPSecrets() {
  4032. const tbody = document.getElementById('secrets-table-body');
  4033. const empty = document.getElementById('secrets-empty');
  4034. if (!tbody) return;
  4035. tbody.innerHTML = '';
  4036. const secrets = state.pppSecrets || [];
  4037. if (secrets.length === 0) {
  4038. empty?.classList.remove('hidden');
  4039. return;
  4040. }
  4041. empty?.classList.add('hidden');
  4042. secrets.forEach(s => {
  4043. const tr = document.createElement('tr');
  4044. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  4045. tr.innerHTML = `
  4046. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  4047. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  4048. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  4049. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  4050. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  4051. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  4052. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  4053. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4054. <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>
  4055. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4056. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  4057. </td>
  4058. `;
  4059. tbody.appendChild(tr);
  4060. });
  4061. }
  4062. async function loadPPPProfiles() {
  4063. try {
  4064. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  4065. const data = await res.json();
  4066. state.pppProfiles = Array.isArray(data) ? data : [];
  4067. const b = document.getElementById('ppp-badge-profiles');
  4068. if (b) b.innerText = state.pppProfiles.length;
  4069. const b2 = document.getElementById('profiles-count-badge');
  4070. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  4071. // Populate profile selects across modals
  4072. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  4073. selects.forEach(sid => {
  4074. const el = document.getElementById(sid);
  4075. if (!el) return;
  4076. const cur = el.value;
  4077. el.innerHTML = '';
  4078. state.pppProfiles.forEach(p => {
  4079. const opt = document.createElement('option');
  4080. opt.value = p.name;
  4081. opt.innerText = `${p.name} (${p.remote_address})`;
  4082. if (p.name === cur) opt.selected = true;
  4083. el.appendChild(opt);
  4084. });
  4085. });
  4086. renderPPPProfiles();
  4087. } catch (err) {
  4088. console.error('Failed to load PPP profiles:', err);
  4089. }
  4090. }
  4091. function renderPPPProfiles() {
  4092. const tbody = document.getElementById('profiles-table-body');
  4093. if (!tbody) return;
  4094. tbody.innerHTML = '';
  4095. (state.pppProfiles || []).forEach(p => {
  4096. const isDefault = p.name.startsWith('default');
  4097. const tr = document.createElement('tr');
  4098. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  4099. tr.innerHTML = `
  4100. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  4101. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  4102. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  4103. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  4104. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  4105. <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>
  4106. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  4107. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  4108. ${!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>`}
  4109. </td>
  4110. `;
  4111. tbody.appendChild(tr);
  4112. });
  4113. }
  4114. async function loadPPPServers() {
  4115. try {
  4116. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  4117. fetch(`${API_BASE}/vpn/servers/pppoe`),
  4118. fetch(`${API_BASE}/vpn/servers/pptp`),
  4119. fetch(`${API_BASE}/vpn/servers/l2tp`),
  4120. fetch(`${API_BASE}/vpn/servers/ipsec`)
  4121. ]);
  4122. if (pppoeRes.ok) {
  4123. state.pppoeServer = await pppoeRes.json();
  4124. const s = state.pppoeServer;
  4125. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  4126. document.getElementById('pppoe-server-name').value = s.service_name || 'proxmox-pppoe';
  4127. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  4128. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  4129. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  4130. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  4131. const pill = document.getElementById('pppoe-server-status-pill');
  4132. if (pill) {
  4133. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  4134. 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';
  4135. }
  4136. setDotBadge('ppp-badge-pppoe-state', s.running);
  4137. }
  4138. if (pptpRes.ok) {
  4139. state.pptpServer = await pptpRes.json();
  4140. const s = state.pptpServer;
  4141. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  4142. document.getElementById('pptp-server-port').value = s.port || 1723;
  4143. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  4144. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  4145. const pill = document.getElementById('pptp-server-status-pill');
  4146. if (pill) {
  4147. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  4148. 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';
  4149. }
  4150. setDotBadge('ppp-badge-pptp-state', s.running);
  4151. }
  4152. if (l2tpRes.ok) {
  4153. state.l2tpServer = await l2tpRes.json();
  4154. const s = state.l2tpServer;
  4155. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  4156. document.getElementById('l2tp-server-port').value = s.port || 1701;
  4157. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  4158. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  4159. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  4160. const pill = document.getElementById('l2tp-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-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';
  4164. }
  4165. setDotBadge('ppp-badge-l2tp-state', s.running);
  4166. }
  4167. if (ipsecRes.ok) {
  4168. state.ipsecServer = await ipsecRes.json();
  4169. const s = state.ipsecServer;
  4170. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  4171. if (modalEn) modalEn.checked = !!s.enabled;
  4172. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  4173. if (modalPsk) modalPsk.value = s.preshared_key || '';
  4174. const modalPool = document.getElementById('modal-ipsec-server-pool');
  4175. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  4176. const modalDns = document.getElementById('modal-ipsec-server-dns');
  4177. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  4178. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  4179. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  4180. const pill = document.getElementById('modal-ipsec-server-status');
  4181. if (pill) {
  4182. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  4183. 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';
  4184. }
  4185. }
  4186. } catch (err) {
  4187. console.error('Failed to load VPN servers:', err);
  4188. }
  4189. }
  4190. async function loadPPPSessions() {
  4191. try {
  4192. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  4193. const data = await res.json();
  4194. state.pppActiveSessions = Array.isArray(data) ? data : [];
  4195. const b = document.getElementById('ppp-badge-active');
  4196. if (b) b.innerText = state.pppActiveSessions.length;
  4197. const sideB = document.getElementById('badge-ppp-sessions');
  4198. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  4199. renderPPPSessions();
  4200. } catch (err) {
  4201. console.error('Failed to load active PPP sessions:', err);
  4202. }
  4203. }
  4204. function renderPPPSessions() {
  4205. const tbody = document.getElementById('active-ppp-table-body');
  4206. const empty = document.getElementById('active-ppp-empty');
  4207. if (!tbody) return;
  4208. tbody.innerHTML = '';
  4209. const list = state.pppActiveSessions || [];
  4210. if (list.length === 0) {
  4211. empty?.classList.remove('hidden');
  4212. return;
  4213. }
  4214. empty?.classList.add('hidden');
  4215. list.forEach(s => {
  4216. const tr = document.createElement('tr');
  4217. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  4218. tr.innerHTML = `
  4219. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  4220. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  4221. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  4222. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  4223. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  4224. <td class="py-2.5 px-3 text-[11px]">
  4225. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  4226. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  4227. </td>
  4228. <td class="py-2.5 px-3 text-right font-sans">
  4229. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  4230. </td>
  4231. `;
  4232. tbody.appendChild(tr);
  4233. });
  4234. }
  4235. async function disconnectPPPSession(iface) {
  4236. if (!confirm(`Disconnect session ${iface}?`)) return;
  4237. try {
  4238. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  4239. if (res.ok) {
  4240. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  4241. loadPPPSessions();
  4242. }
  4243. } catch (err) {
  4244. showToast('Error', err.message, 'error');
  4245. }
  4246. }
  4247. // PPP Secret Modal handlers
  4248. function openAddPPPSecretModal() {
  4249. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  4250. document.getElementById('secret-modal-id').value = '';
  4251. document.getElementById('secret-modal-name').value = '';
  4252. document.getElementById('secret-modal-password').value = '';
  4253. document.getElementById('secret-modal-service').value = 'any';
  4254. document.getElementById('secret-modal-profile').value = 'default';
  4255. document.getElementById('secret-modal-local').value = '';
  4256. document.getElementById('secret-modal-remote').value = '';
  4257. document.getElementById('secret-modal-comment').value = '';
  4258. document.getElementById('secret-modal-disabled').checked = false;
  4259. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  4260. }
  4261. function openEditPPPSecretModal(id) {
  4262. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  4263. if (!s) return;
  4264. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  4265. document.getElementById('secret-modal-id').value = s.id;
  4266. document.getElementById('secret-modal-name').value = s.name;
  4267. document.getElementById('secret-modal-password').value = s.password;
  4268. document.getElementById('secret-modal-service').value = s.service || 'any';
  4269. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  4270. document.getElementById('secret-modal-local').value = s.local_address || '';
  4271. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  4272. document.getElementById('secret-modal-comment').value = s.comment || '';
  4273. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  4274. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  4275. }
  4276. function closePPPSecretModal() {
  4277. document.getElementById('ppp-secret-modal').classList.add('hidden');
  4278. }
  4279. async function submitSavePPPSecret(e) {
  4280. e.preventDefault();
  4281. const id = document.getElementById('secret-modal-id').value;
  4282. const name = document.getElementById('secret-modal-name').value.trim();
  4283. const password = document.getElementById('secret-modal-password').value.trim();
  4284. const service = document.getElementById('secret-modal-service').value;
  4285. const profile = document.getElementById('secret-modal-profile').value;
  4286. const local = document.getElementById('secret-modal-local').value.trim();
  4287. const remote = document.getElementById('secret-modal-remote').value.trim();
  4288. const comment = document.getElementById('secret-modal-comment').value.trim();
  4289. const disabled = document.getElementById('secret-modal-disabled').checked;
  4290. try {
  4291. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  4292. method: 'POST',
  4293. headers: { 'Content-Type': 'application/json' },
  4294. body: JSON.stringify({
  4295. id,
  4296. name,
  4297. password,
  4298. service,
  4299. profile,
  4300. local_address: local,
  4301. remote_address: remote,
  4302. comment,
  4303. disabled
  4304. })
  4305. });
  4306. if (res.ok) {
  4307. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  4308. closePPPSecretModal();
  4309. loadPPPSecrets();
  4310. } else {
  4311. const err = await res.json();
  4312. showToast('Error', err.message, 'error');
  4313. }
  4314. } catch (err) {
  4315. showToast('Error', err.message, 'error');
  4316. }
  4317. }
  4318. async function togglePPPSecretState(id, disabled) {
  4319. try {
  4320. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  4321. method: 'POST',
  4322. headers: { 'Content-Type': 'application/json' },
  4323. body: JSON.stringify({ disabled })
  4324. });
  4325. if (res.ok) {
  4326. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  4327. loadPPPSecrets();
  4328. }
  4329. } catch (err) {
  4330. showToast('Error', err.message, 'error');
  4331. }
  4332. }
  4333. async function deletePPPSecret(id) {
  4334. if (!confirm('Are you sure you want to delete this secret account?')) return;
  4335. try {
  4336. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4337. if (res.ok) {
  4338. showToast('Deleted', 'Secret account removed', 'success');
  4339. loadPPPSecrets();
  4340. }
  4341. } catch (err) {
  4342. showToast('Error', err.message, 'error');
  4343. }
  4344. }
  4345. // PPP Profile Modal handlers
  4346. function openAddPPPProfileModal() {
  4347. document.getElementById('profile-modal-name').value = '';
  4348. document.getElementById('profile-modal-local').value = '10.10.10.1';
  4349. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  4350. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  4351. document.getElementById('profile-modal-encryption').value = 'required';
  4352. document.getElementById('profile-modal-onlyone').checked = true;
  4353. document.getElementById('profile-modal-comment').value = '';
  4354. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  4355. }
  4356. function closePPPProfileModal() {
  4357. document.getElementById('ppp-profile-modal').classList.add('hidden');
  4358. }
  4359. async function submitSavePPPProfile(e) {
  4360. e.preventDefault();
  4361. const name = document.getElementById('profile-modal-name').value.trim();
  4362. const local = document.getElementById('profile-modal-local').value.trim();
  4363. const remote = document.getElementById('profile-modal-remote').value.trim();
  4364. const dns = document.getElementById('profile-modal-dns').value.trim();
  4365. const enc = document.getElementById('profile-modal-encryption').value;
  4366. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  4367. const comment = document.getElementById('profile-modal-comment').value.trim();
  4368. try {
  4369. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  4370. method: 'POST',
  4371. headers: { 'Content-Type': 'application/json' },
  4372. body: JSON.stringify({
  4373. id: name,
  4374. name,
  4375. local_address: local,
  4376. remote_address: remote,
  4377. dns_servers: dns,
  4378. use_encryption: enc,
  4379. only_one: onlyone,
  4380. comment
  4381. })
  4382. });
  4383. if (res.ok) {
  4384. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  4385. closePPPProfileModal();
  4386. loadPPPProfiles();
  4387. } else {
  4388. const err = await res.json();
  4389. showToast('Error', err.message, 'error');
  4390. }
  4391. } catch (err) {
  4392. showToast('Error', err.message, 'error');
  4393. }
  4394. }
  4395. async function deletePPPProfile(name) {
  4396. if (!confirm(`Delete PPP profile ${name}?`)) return;
  4397. try {
  4398. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  4399. if (res.ok) {
  4400. showToast('Deleted', 'Profile removed', 'success');
  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. // Server Config submissions
  4411. async function savePPPoEServerConfig(e) {
  4412. e.preventDefault();
  4413. const enabled = document.getElementById('pppoe-server-enabled').checked;
  4414. const name = document.getElementById('pppoe-server-name').value.trim();
  4415. const iface = document.getElementById('pppoe-server-iface').value;
  4416. const profile = document.getElementById('pppoe-server-profile').value;
  4417. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  4418. const onesession = document.getElementById('pppoe-server-onesession').checked;
  4419. try {
  4420. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  4421. method: 'POST',
  4422. headers: { 'Content-Type': 'application/json' },
  4423. body: JSON.stringify({
  4424. enabled,
  4425. service_name: name,
  4426. interface: iface,
  4427. default_profile: profile,
  4428. max_mtu: mtu,
  4429. max_mru: mtu,
  4430. one_session_per_host: onesession
  4431. })
  4432. });
  4433. if (res.ok) {
  4434. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  4435. loadPPPServers();
  4436. fetchData(false);
  4437. } else {
  4438. const err = await res.json();
  4439. showToast('Error', err.message, 'error');
  4440. }
  4441. } catch (err) {
  4442. showToast('Error', err.message, 'error');
  4443. }
  4444. }
  4445. async function savePPTPServerConfig(e) {
  4446. e.preventDefault();
  4447. const enabled = document.getElementById('pptp-server-enabled').checked;
  4448. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  4449. const profile = document.getElementById('pptp-server-profile').value;
  4450. const mppe = document.getElementById('pptp-server-mppe').checked;
  4451. try {
  4452. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  4453. method: 'POST',
  4454. headers: { 'Content-Type': 'application/json' },
  4455. body: JSON.stringify({
  4456. enabled,
  4457. port,
  4458. default_profile: profile,
  4459. require_mppe: mppe
  4460. })
  4461. });
  4462. if (res.ok) {
  4463. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  4464. loadPPPServers();
  4465. fetchData(false);
  4466. } else {
  4467. const err = await res.json();
  4468. showToast('Error', err.message, 'error');
  4469. }
  4470. } catch (err) {
  4471. showToast('Error', err.message, 'error');
  4472. }
  4473. }
  4474. async function saveL2TPServerConfig(e) {
  4475. e.preventDefault();
  4476. const enabled = document.getElementById('l2tp-server-enabled').checked;
  4477. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  4478. const profile = document.getElementById('l2tp-server-profile').value;
  4479. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  4480. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  4481. try {
  4482. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  4483. method: 'POST',
  4484. headers: { 'Content-Type': 'application/json' },
  4485. body: JSON.stringify({
  4486. enabled,
  4487. port,
  4488. default_profile: profile,
  4489. use_ipsec: useipsec,
  4490. ipsec_secret: psk
  4491. })
  4492. });
  4493. if (res.ok) {
  4494. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  4495. loadPPPServers();
  4496. fetchData(false);
  4497. } else {
  4498. const err = await res.json();
  4499. showToast('Error', err.message, 'error');
  4500. }
  4501. } catch (err) {
  4502. showToast('Error', err.message, 'error');
  4503. }
  4504. }
  4505. // IPSec Server Modal
  4506. function openIPSecServerModal() {
  4507. loadPPPServers();
  4508. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  4509. }
  4510. function closeIPSecServerModal() {
  4511. document.getElementById('ipsec-server-modal').classList.add('hidden');
  4512. }
  4513. async function submitSaveIPSecServer(e) {
  4514. e.preventDefault();
  4515. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  4516. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  4517. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  4518. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  4519. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  4520. try {
  4521. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  4522. method: 'POST',
  4523. headers: { 'Content-Type': 'application/json' },
  4524. body: JSON.stringify({
  4525. enabled,
  4526. preshared_key: psk,
  4527. pool_address: pool,
  4528. dns_servers: dns,
  4529. local_subnet: subnet
  4530. })
  4531. });
  4532. if (res.ok) {
  4533. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  4534. closeIPSecServerModal();
  4535. loadPPPServers();
  4536. fetchData(false);
  4537. } else {
  4538. const err = await res.json();
  4539. showToast('Error', err.message, 'error');
  4540. }
  4541. } catch (err) {
  4542. showToast('Error', err.message, 'error');
  4543. }
  4544. }
  4545. // WireGuard Client Config Viewer
  4546. let currentWGClientConf = '';
  4547. async function openWGClientConfModal(iface, clientIP) {
  4548. try {
  4549. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  4550. method: 'POST',
  4551. headers: { 'Content-Type': 'application/json' },
  4552. body: JSON.stringify({
  4553. interface: iface,
  4554. address: clientIP || '10.10.0.2/32',
  4555. dns: '1.1.1.1, 8.8.8.8'
  4556. })
  4557. });
  4558. if (res.ok) {
  4559. const data = await res.json();
  4560. currentWGClientConf = data.config;
  4561. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  4562. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  4563. } else {
  4564. const err = await res.json();
  4565. showToast('Error', err.message, 'error');
  4566. }
  4567. } catch (err) {
  4568. showToast('Error', err.message, 'error');
  4569. }
  4570. }
  4571. function closeWGClientConfModal() {
  4572. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  4573. }
  4574. function copyWGClientConf() {
  4575. if (!currentWGClientConf) return;
  4576. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  4577. }
  4578. function downloadWGClientConf() {
  4579. if (!currentWGClientConf) return;
  4580. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  4581. const a = document.createElement('a');
  4582. a.href = URL.createObjectURL(blob);
  4583. a.download = 'wireguard-client.conf';
  4584. document.body.appendChild(a);
  4585. a.click();
  4586. document.body.removeChild(a);
  4587. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  4588. }
  4589. // =========================================================================
  4590. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  4591. // =========================================================================
  4592. state.activeDynSubTab = 'bgp-peers';
  4593. state.activeBgpSubTab = 'bgp-peers';
  4594. state.activeOspfSubTab = 'ospf-ifaces';
  4595. state.bgpInstance = null;
  4596. state.bgpPeers = [];
  4597. state.bgpNets = [];
  4598. state.bgpRoutes = [];
  4599. state.ospfInstance = null;
  4600. state.ospfInterfaces = [];
  4601. state.ospfAreas = [];
  4602. state.ospfNeighbors = [];
  4603. state.ospfRoutes = [];
  4604. function switchBgpSubTab(subTab) {
  4605. state.activeBgpSubTab = subTab;
  4606. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes'];
  4607. tabs.forEach(t => {
  4608. const el = document.getElementById(`dyn-subtab-${t}`);
  4609. const btn = document.getElementById(`bgp-subtab-btn-${t}`);
  4610. if (el) el.classList.toggle('hidden', t !== subTab);
  4611. if (btn) {
  4612. if (t === subTab) {
  4613. 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';
  4614. } else {
  4615. 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';
  4616. }
  4617. }
  4618. });
  4619. }
  4620. function switchOspfSubTab(subTab) {
  4621. state.activeOspfSubTab = subTab;
  4622. const tabs = ['ospf-ifaces', 'ospf-areas', 'ospf-nbrs', 'ospf-routes'];
  4623. tabs.forEach(t => {
  4624. const el = document.getElementById(`dyn-subtab-${t}`);
  4625. const btn = document.getElementById(`ospf-subtab-btn-${t}`);
  4626. if (el) el.classList.toggle('hidden', t !== subTab);
  4627. if (btn) {
  4628. if (t === subTab) {
  4629. 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';
  4630. } else {
  4631. 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';
  4632. }
  4633. }
  4634. });
  4635. }
  4636. function switchDynSubTab(subTab) {
  4637. if (subTab.startsWith('bgp')) {
  4638. if (state.activeTab !== 'bgp') navigate('bgp');
  4639. switchBgpSubTab(subTab);
  4640. } else if (subTab.startsWith('ospf')) {
  4641. if (state.activeTab !== 'ospf') navigate('ospf');
  4642. switchOspfSubTab(subTab);
  4643. }
  4644. }
  4645. async function loadDynamicRouting(showToastMsg = false) {
  4646. try {
  4647. const [sumRes, bgpInstRes, bgpPeersRes, bgpNetsRes, bgpRoutesRes, ospfInstRes, ospfIfacesRes, ospfAreasRes, ospfNbrsRes, ospfRoutesRes] = await Promise.all([
  4648. fetch(`${API_BASE}/routing/dynamic/summary`),
  4649. fetch(`${API_BASE}/routing/bgp/instance`),
  4650. fetch(`${API_BASE}/routing/bgp/peers`),
  4651. fetch(`${API_BASE}/routing/bgp/networks`),
  4652. fetch(`${API_BASE}/routing/bgp/routes`),
  4653. fetch(`${API_BASE}/routing/ospf/instance`),
  4654. fetch(`${API_BASE}/routing/ospf/interfaces`),
  4655. fetch(`${API_BASE}/routing/ospf/areas`),
  4656. fetch(`${API_BASE}/routing/ospf/neighbors`),
  4657. fetch(`${API_BASE}/routing/ospf/routes`)
  4658. ]);
  4659. if (sumRes.ok) state.dynSummary = await sumRes.json();
  4660. if (bgpInstRes.ok) state.bgpInstance = await bgpInstRes.json();
  4661. if (bgpPeersRes.ok) state.bgpPeers = await bgpPeersRes.json();
  4662. if (bgpNetsRes.ok) state.bgpNets = await bgpNetsRes.json();
  4663. if (bgpRoutesRes.ok) state.bgpRoutes = await bgpRoutesRes.json();
  4664. if (ospfInstRes.ok) state.ospfInstance = await ospfInstRes.json();
  4665. if (ospfIfacesRes.ok) state.ospfInterfaces = await ospfIfacesRes.json();
  4666. if (ospfAreasRes.ok) state.ospfAreas = await ospfAreasRes.json();
  4667. if (ospfNbrsRes.ok) state.ospfNeighbors = await ospfNbrsRes.json();
  4668. if (ospfRoutesRes.ok) state.ospfRoutes = await ospfRoutesRes.json();
  4669. try { renderBgpStatusPill(); } catch(e) { console.error('renderBgpStatusPill error:', e); }
  4670. try { renderBgpPeers(); } catch(e) { console.error('renderBgpPeers error:', e); }
  4671. try { renderBgpNetworks(); } catch(e) { console.error('renderBgpNetworks error:', e); }
  4672. try { renderBgpRoutes(); } catch(e) { console.error('renderBgpRoutes error:', e); }
  4673. try { renderOspfStatusPill(); } catch(e) { console.error('renderOspfStatusPill error:', e); }
  4674. try { renderOspfInterfaces(); } catch(e) { console.error('renderOspfInterfaces error:', e); }
  4675. try { renderOspfAreas(); } catch(e) { console.error('renderOspfAreas error:', e); }
  4676. try { renderOspfNeighbors(); } catch(e) { console.error('renderOspfNeighbors error:', e); }
  4677. try { renderOspfRoutes(); } catch(e) { console.error('renderOspfRoutes error:', e); }
  4678. try { updateBadges(); } catch(e) { console.error('updateBadges error:', e); }
  4679. if (showToastMsg) showToast('Refreshed', 'Dynamic routing telemetry updated', 'info');
  4680. } catch (err) {
  4681. console.error('Failed to load dynamic routing:', err);
  4682. if (showToastMsg) showToast('Error', 'Failed to load dynamic routing telemetry', 'error');
  4683. }
  4684. }
  4685. function renderBgpStatusPill() {
  4686. const pill = document.getElementById('bgp-live-status-pill');
  4687. if (!pill) return;
  4688. const inst = state.bgpInstance;
  4689. if (!inst || !inst.enabled) {
  4690. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  4691. pill.innerText = 'BGP DISABLED';
  4692. } else if (inst.running) {
  4693. 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';
  4694. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  4695. } else {
  4696. 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';
  4697. pill.innerText = 'BGP STARTING...';
  4698. }
  4699. }
  4700. function renderBgpPeers() {
  4701. const tbody = document.getElementById('bgp-peers-table-body');
  4702. if (!tbody) return;
  4703. const empty = document.getElementById('bgp-peers-empty');
  4704. const countBadge = document.getElementById('bgp-peers-count-badge');
  4705. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  4706. const peers = state.bgpPeers || [];
  4707. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  4708. if (navBadge) navBadge.innerText = peers.length;
  4709. if (peers.length === 0) {
  4710. tbody.innerHTML = '';
  4711. if (empty) empty.classList.remove('hidden');
  4712. return;
  4713. }
  4714. if (empty) empty.classList.add('hidden');
  4715. tbody.innerHTML = peers.map(p => {
  4716. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  4717. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  4718. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  4719. let stateBadge = '';
  4720. if (p.disabled) {
  4721. 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>';
  4722. } else if (p.state === 'Established') {
  4723. 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>';
  4724. } else if (p.state === 'Connect' || p.state === 'Active') {
  4725. 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>`;
  4726. } else {
  4727. 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>`;
  4728. }
  4729. return `
  4730. <tr class="hover:bg-slate-800/40 transition">
  4731. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  4732. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  4733. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  4734. <td class="py-2.5 px-3 font-bold text-slate-200">AS ${p.remote_as}</td>
  4735. <td class="py-2.5 px-3">${stateBadge}</td>
  4736. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  4737. <td class="py-2.5 px-3 text-slate-300">
  4738. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  4739. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  4740. </td>
  4741. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  4742. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  4743. <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'}">
  4744. ${p.disabled ? 'Enable' : 'Disable'}
  4745. </button>
  4746. <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">
  4747. Edit
  4748. </button>
  4749. <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">
  4750. Delete
  4751. </button>
  4752. </td>
  4753. </tr>
  4754. `;
  4755. }).join('');
  4756. }
  4757. function renderBgpNetworks() {
  4758. const tbody = document.getElementById('bgp-nets-table-body');
  4759. if (!tbody) return;
  4760. const empty = document.getElementById('bgp-nets-empty');
  4761. const countBadge = document.getElementById('bgp-nets-count-badge');
  4762. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  4763. const nets = state.bgpNets || [];
  4764. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  4765. if (navBadge) navBadge.innerText = nets.length;
  4766. if (nets.length === 0) {
  4767. tbody.innerHTML = '';
  4768. if (empty) empty.classList.remove('hidden');
  4769. return;
  4770. }
  4771. if (empty) empty.classList.add('hidden');
  4772. tbody.innerHTML = nets.map(n => `
  4773. <tr class="hover:bg-slate-800/40 transition">
  4774. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  4775. <td class="py-2.5 px-3">
  4776. ${n.disabled
  4777. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  4778. : '<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>'}
  4779. </td>
  4780. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  4781. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  4782. <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">
  4783. Delete
  4784. </button>
  4785. </td>
  4786. </tr>
  4787. `).join('');
  4788. }
  4789. function renderBgpRoutes() {
  4790. const tbody = document.getElementById('bgp-routes-table-body');
  4791. if (!tbody) return;
  4792. const empty = document.getElementById('bgp-routes-empty');
  4793. const countBadge = document.getElementById('bgp-routes-count-badge');
  4794. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  4795. const routes = state.bgpRoutes || [];
  4796. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  4797. if (navBadge) navBadge.innerText = routes.length;
  4798. if (routes.length === 0) {
  4799. tbody.innerHTML = '';
  4800. if (empty) empty.classList.remove('hidden');
  4801. return;
  4802. }
  4803. if (empty) empty.classList.add('hidden');
  4804. tbody.innerHTML = routes.map(r => `
  4805. <tr class="hover:bg-slate-800/40 transition">
  4806. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  4807. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  4808. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  4809. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  4810. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  4811. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  4812. </tr>
  4813. `).join('');
  4814. }
  4815. function renderOspfStatusPill() {
  4816. const pill = document.getElementById('ospf-live-status-pill');
  4817. if (!pill) return;
  4818. const inst = state.ospfInstance;
  4819. if (!inst || !inst.enabled) {
  4820. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  4821. pill.innerText = 'OSPF DISABLED';
  4822. } else if (inst.running) {
  4823. 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';
  4824. pill.innerText = `OSPF ACTIVE (ID: ${inst.router_id || 'Auto'})`;
  4825. } else {
  4826. 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';
  4827. pill.innerText = 'OSPF STARTING...';
  4828. }
  4829. }
  4830. function renderOspfInterfaces() {
  4831. const tbody = document.getElementById('ospf-ifaces-table-body');
  4832. if (!tbody) return;
  4833. const empty = document.getElementById('ospf-ifaces-empty');
  4834. const countBadge = document.getElementById('ospf-ifaces-count-badge');
  4835. const navBadge = document.getElementById('dyn-badge-ospf-ifaces');
  4836. const ifaces = state.ospfInterfaces || [];
  4837. if (countBadge) countBadge.innerText = `${ifaces.length} Interfaces`;
  4838. if (navBadge) navBadge.innerText = ifaces.length;
  4839. if (ifaces.length === 0) {
  4840. tbody.innerHTML = '';
  4841. if (empty) empty.classList.remove('hidden');
  4842. return;
  4843. }
  4844. if (empty) empty.classList.add('hidden');
  4845. tbody.innerHTML = ifaces.map(i => {
  4846. let flagA = !i.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  4847. let flagP = i.passive ? '<span class="text-amber-400 font-bold ml-1" title="Passive">P</span>' : '';
  4848. let flagX = i.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  4849. return `
  4850. <tr class="hover:bg-slate-800/40 transition">
  4851. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagP}${flagX}</td>
  4852. <td class="py-2.5 px-3 font-semibold text-white font-mono">${escapeHtml(i.network)}</td>
  4853. <td class="py-2.5 px-3 text-indigo-300 font-bold">Area ${escapeHtml(i.area)}</td>
  4854. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(i.interface || 'Any')}</td>
  4855. <td class="py-2.5 px-3 text-slate-300">${i.cost}</td>
  4856. <td class="py-2.5 px-3 text-slate-300">${i.priority}</td>
  4857. <td class="py-2.5 px-3 text-slate-400">${i.hello_interval}s / ${i.dead_interval}s</td>
  4858. <td class="py-2.5 px-3 text-slate-300 uppercase">${escapeHtml(i.auth_type || 'none')}</td>
  4859. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(i.comment || '')}</td>
  4860. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  4861. <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'}">
  4862. ${i.disabled ? 'Enable' : 'Disable'}
  4863. </button>
  4864. <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">
  4865. Edit
  4866. </button>
  4867. <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">
  4868. Delete
  4869. </button>
  4870. </td>
  4871. </tr>
  4872. `;
  4873. }).join('');
  4874. }
  4875. function renderOspfAreas() {
  4876. const tbody = document.getElementById('ospf-areas-table-body');
  4877. if (!tbody) return;
  4878. const countBadge = document.getElementById('ospf-areas-count-badge');
  4879. const navBadge = document.getElementById('dyn-badge-ospf-areas');
  4880. const areas = state.ospfAreas || [];
  4881. if (countBadge) countBadge.innerText = `${areas.length} Areas`;
  4882. if (navBadge) navBadge.innerText = areas.length;
  4883. tbody.innerHTML = areas.map(a => `
  4884. <tr class="hover:bg-slate-800/40 transition">
  4885. <td class="py-2.5 px-3 font-semibold text-white font-mono">${escapeHtml(a.name)}</td>
  4886. <td class="py-2.5 px-3 font-bold text-indigo-300">${escapeHtml(a.area_id)}</td>
  4887. <td class="py-2.5 px-3 text-slate-300 uppercase">${escapeHtml(a.area_type || 'default')}</td>
  4888. <td class="py-2.5 px-3 text-slate-400 font-sans">${escapeHtml(a.comment || '')}</td>
  4889. <td class="py-2.5 px-3 text-right font-sans">
  4890. <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">
  4891. Delete
  4892. </button>
  4893. </td>
  4894. </tr>
  4895. `).join('');
  4896. }
  4897. function renderOspfNeighbors() {
  4898. const tbody = document.getElementById('ospf-nbrs-table-body');
  4899. if (!tbody) return;
  4900. const empty = document.getElementById('ospf-nbrs-empty');
  4901. const countBadge = document.getElementById('ospf-nbrs-count-badge');
  4902. const navBadge = document.getElementById('dyn-badge-ospf-nbrs');
  4903. const nbrs = state.ospfNeighbors || [];
  4904. if (countBadge) countBadge.innerText = `${nbrs.length} Neighbors`;
  4905. if (navBadge) navBadge.innerText = nbrs.length;
  4906. if (nbrs.length === 0) {
  4907. tbody.innerHTML = '';
  4908. if (empty) empty.classList.remove('hidden');
  4909. return;
  4910. }
  4911. if (empty) empty.classList.add('hidden');
  4912. tbody.innerHTML = nbrs.map(n => {
  4913. let stateBadge = '';
  4914. if (n.state && (n.state.startsWith('Full') || n.state.includes('DR') || n.state.includes('Backup'))) {
  4915. 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>`;
  4916. } else {
  4917. 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>`;
  4918. }
  4919. return `
  4920. <tr class="hover:bg-slate-800/40 transition">
  4921. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(n.neighbor_id)}</td>
  4922. <td class="py-2.5 px-3 text-indigo-300 font-bold">${escapeHtml(n.address)}</td>
  4923. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(n.interface)}</td>
  4924. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(n.area || '0.0.0.0')}</td>
  4925. <td class="py-2.5 px-3">${stateBadge}</td>
  4926. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(n.dead_timer || '-')}</td>
  4927. </tr>
  4928. `;
  4929. }).join('');
  4930. }
  4931. function renderOspfRoutes() {
  4932. const tbody = document.getElementById('ospf-routes-table-body');
  4933. if (!tbody) return;
  4934. const empty = document.getElementById('ospf-routes-empty');
  4935. const countBadge = document.getElementById('ospf-routes-count-badge');
  4936. const navBadge = document.getElementById('dyn-badge-ospf-routes');
  4937. const routes = state.ospfRoutes || [];
  4938. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  4939. if (navBadge) navBadge.innerText = routes.length;
  4940. if (routes.length === 0) {
  4941. tbody.innerHTML = '';
  4942. if (empty) empty.classList.remove('hidden');
  4943. return;
  4944. }
  4945. if (empty) empty.classList.add('hidden');
  4946. tbody.innerHTML = routes.map(r => `
  4947. <tr class="hover:bg-slate-800/40 transition">
  4948. <td class="py-2.5 px-3 font-semibold text-white font-mono">${escapeHtml(r.prefix)}</td>
  4949. <td class="py-2.5 px-3 text-slate-300">${escapeHtml(r.route_type || 'Network')}</td>
  4950. <td class="py-2.5 px-3 text-slate-300">${r.cost}</td>
  4951. <td class="py-2.5 px-3 text-indigo-300 font-bold">Area ${escapeHtml(r.area || '0.0.0.0')}</td>
  4952. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(r.next_hop || r.interface || '-')}</td>
  4953. </tr>
  4954. `).join('');
  4955. }
  4956. // BGP Modals & Actions
  4957. function openBgpInstanceModal() {
  4958. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  4959. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  4960. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  4961. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  4962. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  4963. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  4964. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  4965. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  4966. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  4967. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  4968. }
  4969. function closeBgpInstanceModal() {
  4970. document.getElementById('bgp-instance-modal').classList.add('hidden');
  4971. }
  4972. async function submitBgpInstance(e) {
  4973. e.preventDefault();
  4974. const payload = {
  4975. enabled: document.getElementById('modal-bgp-enabled').checked,
  4976. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  4977. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  4978. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  4979. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  4980. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  4981. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  4982. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  4983. };
  4984. try {
  4985. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  4986. method: 'POST',
  4987. headers: { 'Content-Type': 'application/json' },
  4988. body: JSON.stringify(payload)
  4989. });
  4990. if (res.ok) {
  4991. closeBgpInstanceModal();
  4992. showToast('Success', 'BGP instance configuration updated', 'success');
  4993. loadDynamicRouting();
  4994. } else {
  4995. const err = await res.json();
  4996. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  4997. }
  4998. } catch (err) {
  4999. showToast('Error', err.message, 'error');
  5000. }
  5001. }
  5002. function openAddBgpPeerModal() {
  5003. document.getElementById('bgp-peer-form').reset();
  5004. document.getElementById('modal-bgp-peer-id').value = '';
  5005. document.getElementById('bgp-peer-modal-title').innerText = 'Add BGP Peer Connection';
  5006. document.getElementById('modal-bgp-peer-nexthop-self').checked = true;
  5007. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  5008. }
  5009. function openEditBgpPeerModal(id) {
  5010. const p = (state.bgpPeers || []).find(item => item.id === id);
  5011. if (!p) return;
  5012. document.getElementById('modal-bgp-peer-id').value = p.id;
  5013. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  5014. document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  5015. document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  5016. document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  5017. document.getElementById('modal-bgp-peer-password').value = p.password || '';
  5018. document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  5019. document.getElementById('modal-bgp-peer-nexthop-self').checked = !!p.nexthop_self;
  5020. document.getElementById('modal-bgp-peer-passive').checked = !!p.passive;
  5021. document.getElementById('modal-bgp-peer-disabled').checked = !!p.disabled;
  5022. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  5023. document.getElementById('bgp-peer-modal-title').innerText = 'Edit BGP Peer Connection';
  5024. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  5025. }
  5026. function closeBgpPeerModal() {
  5027. document.getElementById('bgp-peer-modal').classList.add('hidden');
  5028. }
  5029. async function submitBgpPeer(e) {
  5030. e.preventDefault();
  5031. const payload = {
  5032. id: document.getElementById('modal-bgp-peer-id').value,
  5033. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  5034. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  5035. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10),
  5036. local_address: document.getElementById('modal-bgp-peer-local-addr').value.trim(),
  5037. password: document.getElementById('modal-bgp-peer-password').value,
  5038. multihop: document.getElementById('modal-bgp-peer-multihop').checked,
  5039. nexthop_self: document.getElementById('modal-bgp-peer-nexthop-self').checked,
  5040. passive: document.getElementById('modal-bgp-peer-passive').checked,
  5041. disabled: document.getElementById('modal-bgp-peer-disabled').checked,
  5042. comment: document.getElementById('modal-bgp-peer-comment').value.trim()
  5043. };
  5044. try {
  5045. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  5046. method: 'POST',
  5047. headers: { 'Content-Type': 'application/json' },
  5048. body: JSON.stringify(payload)
  5049. });
  5050. if (res.ok) {
  5051. closeBgpPeerModal();
  5052. showToast('Success', 'BGP Peer saved', 'success');
  5053. loadDynamicRouting();
  5054. } else {
  5055. const err = await res.json();
  5056. showToast('Error', err.error || 'Failed to save peer', 'error');
  5057. }
  5058. } catch (err) {
  5059. showToast('Error', err.message, 'error');
  5060. }
  5061. }
  5062. async function deleteBgpPeer(id) {
  5063. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  5064. try {
  5065. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5066. if (res.ok) {
  5067. showToast('Deleted', 'BGP peer removed', 'success');
  5068. loadDynamicRouting();
  5069. }
  5070. } catch (err) {
  5071. showToast('Error', err.message, 'error');
  5072. }
  5073. }
  5074. async function toggleBgpPeerState(id, disabled) {
  5075. try {
  5076. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  5077. method: 'POST',
  5078. headers: { 'Content-Type': 'application/json' },
  5079. body: JSON.stringify({ disabled })
  5080. });
  5081. if (res.ok) {
  5082. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  5083. loadDynamicRouting();
  5084. }
  5085. } catch (err) {
  5086. showToast('Error', err.message, 'error');
  5087. }
  5088. }
  5089. function openAddBgpNetworkModal() {
  5090. document.getElementById('bgp-network-form').reset();
  5091. document.getElementById('modal-bgp-net-id').value = '';
  5092. document.getElementById('bgp-network-modal').classList.remove('hidden');
  5093. }
  5094. function closeBgpNetworkModal() {
  5095. document.getElementById('bgp-network-modal').classList.add('hidden');
  5096. }
  5097. async function submitBgpNetwork(e) {
  5098. e.preventDefault();
  5099. const payload = {
  5100. id: document.getElementById('modal-bgp-net-id').value,
  5101. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  5102. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  5103. disabled: document.getElementById('modal-bgp-net-disabled').checked
  5104. };
  5105. try {
  5106. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  5107. method: 'POST',
  5108. headers: { 'Content-Type': 'application/json' },
  5109. body: JSON.stringify(payload)
  5110. });
  5111. if (res.ok) {
  5112. closeBgpNetworkModal();
  5113. showToast('Success', 'BGP network advertisement saved', 'success');
  5114. loadDynamicRouting();
  5115. } else {
  5116. const err = await res.json();
  5117. showToast('Error', err.error || 'Failed to save network', 'error');
  5118. }
  5119. } catch (err) {
  5120. showToast('Error', err.message, 'error');
  5121. }
  5122. }
  5123. async function deleteBgpNetwork(id) {
  5124. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  5125. try {
  5126. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5127. if (res.ok) {
  5128. showToast('Deleted', 'Network advertisement removed', 'success');
  5129. loadDynamicRouting();
  5130. }
  5131. } catch (err) {
  5132. showToast('Error', err.message, 'error');
  5133. }
  5134. }
  5135. // OSPF Modals & Actions
  5136. function openOspfInstanceModal() {
  5137. const inst = state.ospfInstance || { enabled: false, router_id: '192.168.131.56', default_metric: 10 };
  5138. document.getElementById('modal-ospf-enabled').checked = !!inst.enabled;
  5139. document.getElementById('modal-ospf-router-id').value = inst.router_id || '';
  5140. document.getElementById('modal-ospf-metric').value = inst.default_metric || 10;
  5141. document.getElementById('modal-ospf-redist-conn').checked = !!inst.redistribute_connected;
  5142. document.getElementById('modal-ospf-redist-static').checked = !!inst.redistribute_static;
  5143. document.getElementById('modal-ospf-redist-bgp').checked = !!inst.redistribute_bgp;
  5144. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  5145. }
  5146. function closeOspfInstanceModal() {
  5147. document.getElementById('ospf-instance-modal').classList.add('hidden');
  5148. }
  5149. async function submitOspfInstance(e) {
  5150. e.preventDefault();
  5151. const payload = {
  5152. enabled: document.getElementById('modal-ospf-enabled').checked,
  5153. router_id: document.getElementById('modal-ospf-router-id').value.trim(),
  5154. default_metric: parseInt(document.getElementById('modal-ospf-metric').value, 10),
  5155. redistribute_connected: document.getElementById('modal-ospf-redist-conn').checked,
  5156. redistribute_static: document.getElementById('modal-ospf-redist-static').checked,
  5157. redistribute_bgp: document.getElementById('modal-ospf-redist-bgp').checked
  5158. };
  5159. try {
  5160. const res = await fetch(`${API_BASE}/routing/ospf/instance`, {
  5161. method: 'POST',
  5162. headers: { 'Content-Type': 'application/json' },
  5163. body: JSON.stringify(payload)
  5164. });
  5165. if (res.ok) {
  5166. closeOspfInstanceModal();
  5167. showToast('Success', 'OSPF instance configuration updated', 'success');
  5168. loadDynamicRouting();
  5169. } else {
  5170. const err = await res.json();
  5171. showToast('Error', err.error || 'Failed to update OSPF instance', 'error');
  5172. }
  5173. } catch (err) {
  5174. showToast('Error', err.message, 'error');
  5175. }
  5176. }
  5177. function openAddOspfAreaModal() {
  5178. document.getElementById('ospf-area-form').reset();
  5179. document.getElementById('modal-ospf-area-id').value = '';
  5180. document.getElementById('modal-ospf-area-areaid').value = '0.0.0.0';
  5181. document.getElementById('ospf-area-modal').classList.remove('hidden');
  5182. }
  5183. function closeOspfAreaModal() {
  5184. document.getElementById('ospf-area-modal').classList.add('hidden');
  5185. }
  5186. async function submitOspfArea(e) {
  5187. e.preventDefault();
  5188. const payload = {
  5189. id: document.getElementById('modal-ospf-area-id').value,
  5190. name: document.getElementById('modal-ospf-area-name').value.trim(),
  5191. area_id: document.getElementById('modal-ospf-area-areaid').value.trim(),
  5192. area_type: document.getElementById('modal-ospf-area-type').value,
  5193. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  5194. };
  5195. try {
  5196. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  5197. method: 'POST',
  5198. headers: { 'Content-Type': 'application/json' },
  5199. body: JSON.stringify(payload)
  5200. });
  5201. if (res.ok) {
  5202. closeOspfAreaModal();
  5203. showToast('Success', 'OSPF area saved', 'success');
  5204. loadDynamicRouting();
  5205. } else {
  5206. const err = await res.json();
  5207. showToast('Error', err.error || 'Failed to save area', 'error');
  5208. }
  5209. } catch (err) {
  5210. showToast('Error', err.message, 'error');
  5211. }
  5212. }
  5213. async function deleteOspfArea(id) {
  5214. if (!confirm('Are you sure you want to delete this OSPF area?')) return;
  5215. try {
  5216. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5217. if (res.ok) {
  5218. showToast('Deleted', 'OSPF area removed', 'success');
  5219. loadDynamicRouting();
  5220. }
  5221. } catch (err) {
  5222. showToast('Error', err.message, 'error');
  5223. }
  5224. }
  5225. function populateOspfInterfaceDevices() {
  5226. const select = document.getElementById('modal-ospf-iface-device');
  5227. if (!select) return;
  5228. const current = select.value;
  5229. select.innerHTML = '<option value="">Any matching interface</option>';
  5230. (state.interfaces || []).forEach(iface => {
  5231. select.innerHTML += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)} (${iface.type})</option>`;
  5232. });
  5233. if (current) select.value = current;
  5234. }
  5235. function openAddOspfInterfaceModal() {
  5236. document.getElementById('ospf-interface-form').reset();
  5237. document.getElementById('modal-ospf-iface-id').value = '';
  5238. document.getElementById('modal-ospf-iface-area').value = '0.0.0.0';
  5239. document.getElementById('modal-ospf-iface-cost').value = '10';
  5240. document.getElementById('modal-ospf-iface-priority').value = '1';
  5241. document.getElementById('modal-ospf-iface-hello').value = '10';
  5242. document.getElementById('modal-ospf-iface-dead').value = '40';
  5243. document.getElementById('ospf-interface-modal-title').innerText = 'Add OSPF Interface';
  5244. populateOspfInterfaceDevices();
  5245. document.getElementById('ospf-interface-modal').classList.remove('hidden');
  5246. }
  5247. function openEditOspfInterfaceModal(id) {
  5248. const item = (state.ospfInterfaces || []).find(i => i.id === id);
  5249. if (!item) return;
  5250. populateOspfInterfaceDevices();
  5251. document.getElementById('modal-ospf-iface-id').value = item.id;
  5252. document.getElementById('modal-ospf-iface-net').value = item.network || '';
  5253. document.getElementById('modal-ospf-iface-area').value = item.area || '0.0.0.0';
  5254. document.getElementById('modal-ospf-iface-device').value = item.interface || '';
  5255. document.getElementById('modal-ospf-iface-cost').value = item.cost || 10;
  5256. document.getElementById('modal-ospf-iface-priority').value = item.priority || 1;
  5257. document.getElementById('modal-ospf-iface-hello').value = item.hello_interval || 10;
  5258. document.getElementById('modal-ospf-iface-dead').value = item.dead_interval || 40;
  5259. document.getElementById('modal-ospf-iface-auth-type').value = item.auth_type || 'none';
  5260. document.getElementById('modal-ospf-iface-auth-key').value = item.auth_key || '';
  5261. document.getElementById('modal-ospf-iface-passive').checked = !!item.passive;
  5262. document.getElementById('modal-ospf-iface-disabled').checked = !!item.disabled;
  5263. document.getElementById('modal-ospf-iface-comment').value = item.comment || '';
  5264. document.getElementById('ospf-interface-modal-title').innerText = 'Edit OSPF Interface';
  5265. document.getElementById('ospf-interface-modal').classList.remove('hidden');
  5266. }
  5267. function closeOspfInterfaceModal() {
  5268. document.getElementById('ospf-interface-modal').classList.add('hidden');
  5269. }
  5270. async function submitOspfInterface(e) {
  5271. e.preventDefault();
  5272. const payload = {
  5273. id: document.getElementById('modal-ospf-iface-id').value,
  5274. network: document.getElementById('modal-ospf-iface-net').value.trim(),
  5275. area: document.getElementById('modal-ospf-iface-area').value.trim(),
  5276. interface: document.getElementById('modal-ospf-iface-device').value,
  5277. cost: parseInt(document.getElementById('modal-ospf-iface-cost').value, 10),
  5278. priority: parseInt(document.getElementById('modal-ospf-iface-priority').value, 10),
  5279. hello_interval: parseInt(document.getElementById('modal-ospf-iface-hello').value, 10),
  5280. dead_interval: parseInt(document.getElementById('modal-ospf-iface-dead').value, 10),
  5281. auth_type: document.getElementById('modal-ospf-iface-auth-type').value,
  5282. auth_key: document.getElementById('modal-ospf-iface-auth-key').value,
  5283. passive: document.getElementById('modal-ospf-iface-passive').checked,
  5284. disabled: document.getElementById('modal-ospf-iface-disabled').checked,
  5285. comment: document.getElementById('modal-ospf-iface-comment').value.trim()
  5286. };
  5287. try {
  5288. const res = await fetch(`${API_BASE}/routing/ospf/interfaces`, {
  5289. method: 'POST',
  5290. headers: { 'Content-Type': 'application/json' },
  5291. body: JSON.stringify(payload)
  5292. });
  5293. if (res.ok) {
  5294. closeOspfInterfaceModal();
  5295. showToast('Success', 'OSPF interface template saved', 'success');
  5296. loadDynamicRouting();
  5297. } else {
  5298. const err = await res.json();
  5299. showToast('Error', err.error || 'Failed to save interface', 'error');
  5300. }
  5301. } catch (err) {
  5302. showToast('Error', err.message, 'error');
  5303. }
  5304. }
  5305. async function deleteOspfInterface(id) {
  5306. if (!confirm('Are you sure you want to delete this OSPF interface?')) return;
  5307. try {
  5308. const res = await fetch(`${API_BASE}/routing/ospf/interfaces/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5309. if (res.ok) {
  5310. showToast('Deleted', 'OSPF interface removed', 'success');
  5311. loadDynamicRouting();
  5312. }
  5313. } catch (err) {
  5314. showToast('Error', err.message, 'error');
  5315. }
  5316. }
  5317. async function toggleOspfInterfaceState(id, disabled) {
  5318. try {
  5319. const res = await fetch(`${API_BASE}/routing/ospf/interfaces/${encodeURIComponent(id)}/state`, {
  5320. method: 'POST',
  5321. headers: { 'Content-Type': 'application/json' },
  5322. body: JSON.stringify({ disabled })
  5323. });
  5324. if (res.ok) {
  5325. showToast('Updated', `Interface ${disabled ? 'disabled' : 'enabled'}`, 'success');
  5326. loadDynamicRouting();
  5327. }
  5328. } catch (err) {
  5329. showToast('Error', err.message, 'error');
  5330. }
  5331. }
  5332. // ============================================================================
  5333. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  5334. // ============================================================================
  5335. function switchBridgeSubTab(tab) {
  5336. state.bridgeSubTab = tab;
  5337. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  5338. tabs.forEach(t => {
  5339. const panel = document.getElementById(`bridge-subtab-${t}`);
  5340. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  5341. if (panel) {
  5342. if (t === tab) panel.classList.remove('hidden');
  5343. else panel.classList.add('hidden');
  5344. }
  5345. if (btn) {
  5346. if (t === tab) {
  5347. 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';
  5348. } else {
  5349. 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';
  5350. }
  5351. }
  5352. });
  5353. const addBtn = document.getElementById('bridge-top-action-btn');
  5354. if (addBtn) {
  5355. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  5356. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  5357. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  5358. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  5359. }
  5360. if (tab === 'hosts') loadBridgeHosts();
  5361. }
  5362. function openCurrentBridgeModal() {
  5363. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  5364. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  5365. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  5366. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  5367. }
  5368. async function loadBridge() {
  5369. try {
  5370. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vlanIfacesRes] = await Promise.all([
  5371. fetch(`${API_BASE}/bridge/bridges`),
  5372. fetch(`${API_BASE}/bridge/ports`),
  5373. fetch(`${API_BASE}/bridge/vlans`),
  5374. fetch(`${API_BASE}/bridge/summary`),
  5375. fetch(`${API_BASE}/vpn/eoip`),
  5376. fetch(`${API_BASE}/vlans`)
  5377. ]);
  5378. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  5379. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  5380. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  5381. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  5382. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  5383. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  5384. // Badges & Stats
  5385. const bBridges = document.getElementById('bridge-badge-bridges');
  5386. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  5387. const bPorts = document.getElementById('bridge-badge-ports');
  5388. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  5389. const bVlans = document.getElementById('bridge-badge-vlans');
  5390. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  5391. const bHosts = document.getElementById('bridge-badge-hosts');
  5392. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  5393. const sBr = document.getElementById('bridge-stat-bridges');
  5394. if (sBr) sBr.innerText = (state.bridges || []).length;
  5395. const sPorts = document.getElementById('bridge-stat-ports');
  5396. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  5397. const sHosts = document.getElementById('bridge-stat-hosts');
  5398. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  5399. renderBridges();
  5400. renderBridgePorts();
  5401. renderBridgeVLANs();
  5402. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  5403. } catch (err) {
  5404. console.error('Failed to load bridge subsystem:', err);
  5405. }
  5406. }
  5407. // ----------------- Bridges -----------------
  5408. function renderBridges() {
  5409. const tbody = document.getElementById('bridge-table-body');
  5410. const empty = document.getElementById('bridge-empty-bridges');
  5411. const countBadge = document.getElementById('bridge-count-badge');
  5412. if (!tbody) return;
  5413. tbody.innerHTML = '';
  5414. const bridges = state.bridges || [];
  5415. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  5416. if (bridges.length === 0) {
  5417. empty?.classList.remove('hidden');
  5418. return;
  5419. }
  5420. empty?.classList.add('hidden');
  5421. bridges.forEach((b, idx) => {
  5422. const tr = document.createElement('tr');
  5423. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  5424. // Format IP addresses pill list
  5425. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  5426. if (b.ip_addresses && b.ip_addresses.length > 0) {
  5427. ipsHtml = b.ip_addresses.map(ip => `
  5428. <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">
  5429. <span>${ip}</span>
  5430. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  5431. </span>
  5432. `).join(' ');
  5433. }
  5434. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  5435. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  5436. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  5437. tr.innerHTML = `
  5438. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  5439. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  5440. <td class="py-2.5 px-3 font-bold text-white text-sm">
  5441. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  5442. </td>
  5443. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  5444. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  5445. <td class="py-2.5 px-3">
  5446. <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>
  5447. </td>
  5448. <td class="py-2.5 px-3 text-center">
  5449. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  5450. </td>
  5451. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  5452. <td class="py-2.5 px-3">
  5453. <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>
  5454. </td>
  5455. <td class="py-2.5 px-3">
  5456. <div class="flex items-center gap-1.5 flex-wrap">
  5457. ${ipsHtml}
  5458. <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>
  5459. </div>
  5460. </td>
  5461. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  5462. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  5463. </td>
  5464. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  5465. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  5466. <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>
  5467. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  5468. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5469. </td>
  5470. `;
  5471. tbody.appendChild(tr);
  5472. });
  5473. }
  5474. function openAddBridgeModal() {
  5475. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  5476. document.getElementById('bridge-modal-id').value = '';
  5477. document.getElementById('bridge-modal-name').value = 'bridge1';
  5478. document.getElementById('bridge-modal-name').disabled = false;
  5479. document.getElementById('bridge-modal-mtu').value = '1500';
  5480. document.getElementById('bridge-modal-mac').value = '';
  5481. document.getElementById('bridge-modal-stp').value = 'rstp';
  5482. document.getElementById('bridge-modal-priority').value = '32768';
  5483. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  5484. document.getElementById('bridge-modal-pvid').value = '1';
  5485. document.getElementById('bridge-modal-fastforward').checked = true;
  5486. document.getElementById('bridge-modal-comment').value = '';
  5487. document.getElementById('bridge-modal-disabled').checked = false;
  5488. toggleBridgeModalVlanFiltering();
  5489. document.getElementById('bridge-modal').classList.remove('hidden');
  5490. }
  5491. function openEditBridgeModal(id) {
  5492. const b = (state.bridges || []).find(x => x.id === id);
  5493. if (!b) return;
  5494. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  5495. document.getElementById('bridge-modal-id').value = b.id;
  5496. document.getElementById('bridge-modal-name').value = b.name;
  5497. document.getElementById('bridge-modal-name').disabled = true;
  5498. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  5499. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  5500. document.getElementById('bridge-modal-stp').value = b.stp || 'rstp';
  5501. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  5502. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  5503. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  5504. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  5505. document.getElementById('bridge-modal-comment').value = b.comment || '';
  5506. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  5507. toggleBridgeModalVlanFiltering();
  5508. document.getElementById('bridge-modal').classList.remove('hidden');
  5509. }
  5510. function closeBridgeModal() {
  5511. document.getElementById('bridge-modal').classList.add('hidden');
  5512. }
  5513. function toggleBridgeModalVlanFiltering() {
  5514. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  5515. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  5516. if (pvidBox) {
  5517. if (chk) pvidBox.classList.remove('opacity-40');
  5518. else pvidBox.classList.add('opacity-40');
  5519. }
  5520. }
  5521. async function submitSaveBridge(e) {
  5522. e.preventDefault();
  5523. const id = document.getElementById('bridge-modal-id').value;
  5524. const name = document.getElementById('bridge-modal-name').value.trim();
  5525. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  5526. const mac = document.getElementById('bridge-modal-mac').value.trim();
  5527. const stp = document.getElementById('bridge-modal-stp').value;
  5528. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  5529. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  5530. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  5531. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  5532. const comment = document.getElementById('bridge-modal-comment').value.trim();
  5533. const disabled = document.getElementById('bridge-modal-disabled').checked;
  5534. try {
  5535. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  5536. method: 'POST',
  5537. headers: { 'Content-Type': 'application/json' },
  5538. body: JSON.stringify({
  5539. id,
  5540. name,
  5541. mtu,
  5542. mac_address: mac,
  5543. stp,
  5544. priority,
  5545. vlan_filtering: vlanFiltering,
  5546. pvid,
  5547. fast_forward: fastForward,
  5548. comment,
  5549. disabled
  5550. })
  5551. });
  5552. if (res.ok) {
  5553. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  5554. closeBridgeModal();
  5555. loadBridge();
  5556. fetchData(false);
  5557. } else {
  5558. const err = await res.json();
  5559. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  5560. }
  5561. } catch (err) {
  5562. showToast('Error', err.message, 'error');
  5563. }
  5564. }
  5565. async function toggleBridgeState(id, disabled) {
  5566. try {
  5567. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  5568. method: 'POST',
  5569. headers: { 'Content-Type': 'application/json' },
  5570. body: JSON.stringify({ disabled })
  5571. });
  5572. if (res.ok) {
  5573. loadBridge();
  5574. fetchData(false);
  5575. }
  5576. } catch (err) {
  5577. showToast('Error', err.message, 'error');
  5578. }
  5579. }
  5580. async function deleteBridge(id) {
  5581. const b = (state.bridges || []).find(x => x.id === id);
  5582. const name = b ? b.name : id;
  5583. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  5584. try {
  5585. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5586. if (res.ok) {
  5587. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  5588. loadBridge();
  5589. fetchData(false);
  5590. } else {
  5591. const err = await res.json();
  5592. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  5593. }
  5594. } catch (err) {
  5595. showToast('Error', err.message, 'error');
  5596. }
  5597. }
  5598. // ----------------- Bridge IP Assignments -----------------
  5599. function openAddBridgeIPModal(id, name) {
  5600. document.getElementById('bridge-ip-modal-id').value = id;
  5601. document.getElementById('bridge-ip-modal-sub').innerText = name;
  5602. document.getElementById('bridge-ip-modal-cidr').value = '';
  5603. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  5604. }
  5605. function closeBridgeIPModal() {
  5606. document.getElementById('bridge-ip-modal').classList.add('hidden');
  5607. }
  5608. async function submitAddBridgeIP(e) {
  5609. e.preventDefault();
  5610. const id = document.getElementById('bridge-ip-modal-id').value;
  5611. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  5612. try {
  5613. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  5614. method: 'POST',
  5615. headers: { 'Content-Type': 'application/json' },
  5616. body: JSON.stringify({ ip })
  5617. });
  5618. if (res.ok) {
  5619. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  5620. closeBridgeIPModal();
  5621. loadBridge();
  5622. fetchData(false);
  5623. } else {
  5624. const err = await res.json();
  5625. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  5626. }
  5627. } catch (err) {
  5628. showToast('Error', err.message, 'error');
  5629. }
  5630. }
  5631. async function deleteBridgeIP(id, ip) {
  5632. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  5633. try {
  5634. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  5635. method: 'DELETE',
  5636. headers: { 'Content-Type': 'application/json' },
  5637. body: JSON.stringify({ ip })
  5638. });
  5639. if (res.ok) {
  5640. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  5641. loadBridge();
  5642. fetchData(false);
  5643. }
  5644. } catch (err) {
  5645. showToast('Error', err.message, 'error');
  5646. }
  5647. }
  5648. // ----------------- Bridge Ports -----------------
  5649. function renderBridgePorts() {
  5650. const tbody = document.getElementById('bridge-ports-table-body');
  5651. const empty = document.getElementById('bridge-empty-ports');
  5652. const countBadge = document.getElementById('bridge-ports-count-badge');
  5653. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  5654. if (!tbody) return;
  5655. tbody.innerHTML = '';
  5656. // Update filter select
  5657. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  5658. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  5659. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  5660. if (ports.length === 0) {
  5661. empty?.classList.remove('hidden');
  5662. return;
  5663. }
  5664. empty?.classList.add('hidden');
  5665. ports.forEach((p, idx) => {
  5666. const tr = document.createElement('tr');
  5667. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  5668. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  5669. tr.innerHTML = `
  5670. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  5671. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  5672. <td class="py-2.5 px-3 font-bold text-white text-sm">
  5673. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  5674. </td>
  5675. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  5676. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  5677. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  5678. <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>
  5679. <td class="py-2.5 px-3">
  5680. ${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>'}
  5681. </td>
  5682. <td class="py-2.5 px-3">
  5683. <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>
  5684. </td>
  5685. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  5686. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  5687. <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>
  5688. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  5689. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5690. </td>
  5691. `;
  5692. tbody.appendChild(tr);
  5693. });
  5694. }
  5695. function openAddBridgePortModal() {
  5696. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  5697. document.getElementById('bridge-port-modal-id').value = '';
  5698. populateBridgeSelect('bridge-port-modal-bridge');
  5699. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  5700. document.getElementById('bridge-port-modal-pvid').value = '1';
  5701. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  5702. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  5703. document.getElementById('bridge-port-modal-horizon').value = '0';
  5704. document.getElementById('bridge-port-modal-pathcost').value = '10';
  5705. document.getElementById('bridge-port-modal-priority').value = '128';
  5706. document.getElementById('bridge-port-modal-learn').checked = true;
  5707. document.getElementById('bridge-port-modal-comment').value = '';
  5708. document.getElementById('bridge-port-modal-disabled').checked = false;
  5709. document.getElementById('bridge-port-modal').classList.remove('hidden');
  5710. }
  5711. function openEditBridgePortModal(id) {
  5712. const p = (state.bridgePorts || []).find(x => x.id === id);
  5713. if (!p) return;
  5714. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  5715. document.getElementById('bridge-port-modal-id').value = p.id;
  5716. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  5717. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  5718. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  5719. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  5720. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  5721. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  5722. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  5723. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  5724. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  5725. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  5726. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  5727. document.getElementById('bridge-port-modal').classList.remove('hidden');
  5728. }
  5729. function closeBridgePortModal() {
  5730. document.getElementById('bridge-port-modal').classList.add('hidden');
  5731. }
  5732. async function submitSaveBridgePort(e) {
  5733. e.preventDefault();
  5734. const id = document.getElementById('bridge-port-modal-id').value;
  5735. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  5736. const iface = document.getElementById('bridge-port-modal-interface').value;
  5737. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  5738. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  5739. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  5740. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  5741. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  5742. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  5743. const learn = document.getElementById('bridge-port-modal-learn').checked;
  5744. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  5745. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  5746. try {
  5747. const res = await fetch(`${API_BASE}/bridge/ports`, {
  5748. method: 'POST',
  5749. headers: { 'Content-Type': 'application/json' },
  5750. body: JSON.stringify({
  5751. id,
  5752. bridge,
  5753. interface: iface,
  5754. pvid,
  5755. frame_types: frameTypes,
  5756. ingress_filtering: ingressFiltering,
  5757. horizon,
  5758. path_cost: pathCost,
  5759. priority,
  5760. learn,
  5761. comment,
  5762. disabled
  5763. })
  5764. });
  5765. if (res.ok) {
  5766. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  5767. closeBridgePortModal();
  5768. loadBridge();
  5769. fetchData(false);
  5770. } else {
  5771. const err = await res.json();
  5772. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  5773. }
  5774. } catch (err) {
  5775. showToast('Error', err.message, 'error');
  5776. }
  5777. }
  5778. async function toggleBridgePortState(id, disabled) {
  5779. try {
  5780. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  5781. method: 'POST',
  5782. headers: { 'Content-Type': 'application/json' },
  5783. body: JSON.stringify({ disabled })
  5784. });
  5785. if (res.ok) {
  5786. loadBridge();
  5787. fetchData(false);
  5788. }
  5789. } catch (err) {
  5790. showToast('Error', err.message, 'error');
  5791. }
  5792. }
  5793. async function deleteBridgePort(id) {
  5794. const p = (state.bridgePorts || []).find(x => x.id === id);
  5795. const iface = p ? p.interface : id;
  5796. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  5797. try {
  5798. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5799. if (res.ok) {
  5800. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  5801. loadBridge();
  5802. fetchData(false);
  5803. }
  5804. } catch (err) {
  5805. showToast('Error', err.message, 'error');
  5806. }
  5807. }
  5808. // ----------------- Bridge VLANs -----------------
  5809. function renderBridgeVLANs() {
  5810. const tbody = document.getElementById('bridge-vlans-table-body');
  5811. const empty = document.getElementById('bridge-empty-vlans');
  5812. const countBadge = document.getElementById('bridge-vlans-count-badge');
  5813. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  5814. if (!tbody) return;
  5815. tbody.innerHTML = '';
  5816. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  5817. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  5818. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  5819. if (vlans.length === 0) {
  5820. empty?.classList.remove('hidden');
  5821. return;
  5822. }
  5823. empty?.classList.add('hidden');
  5824. vlans.forEach((v, idx) => {
  5825. const tr = document.createElement('tr');
  5826. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  5827. const taggedHtml = (v.tagged && v.tagged.length > 0)
  5828. ? 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(' ')
  5829. : '<span class="text-slate-600">none</span>';
  5830. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  5831. ? 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(' ')
  5832. : '<span class="text-slate-600">none</span>';
  5833. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  5834. tr.innerHTML = `
  5835. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  5836. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  5837. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  5838. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  5839. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  5840. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  5841. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  5842. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  5843. <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>
  5844. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  5845. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5846. </td>
  5847. `;
  5848. tbody.appendChild(tr);
  5849. });
  5850. }
  5851. function openAddBridgeVLANModal() {
  5852. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  5853. document.getElementById('bridge-vlan-modal-id').value = '';
  5854. populateBridgeSelect('bridge-vlan-modal-bridge');
  5855. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  5856. document.getElementById('bridge-vlan-modal-comment').value = '';
  5857. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  5858. updateBridgeVlanPortCheckboxes();
  5859. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  5860. }
  5861. function openEditBridgeVLANModal(id) {
  5862. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  5863. if (!v) return;
  5864. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  5865. document.getElementById('bridge-vlan-modal-id').value = v.id;
  5866. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  5867. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  5868. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  5869. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  5870. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  5871. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  5872. }
  5873. function closeBridgeVlanModal() {
  5874. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  5875. }
  5876. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  5877. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  5878. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  5879. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  5880. if (!taggedBox || !untaggedBox) return;
  5881. // Ports belonging to the selected bridge
  5882. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  5883. if (memberPorts.length === 0) {
  5884. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  5885. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  5886. return;
  5887. }
  5888. taggedBox.innerHTML = memberPorts.map(p => `
  5889. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  5890. <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">
  5891. <span>${p.interface}</span>
  5892. </label>
  5893. `).join('');
  5894. untaggedBox.innerHTML = memberPorts.map(p => `
  5895. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  5896. <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">
  5897. <span>${p.interface}</span>
  5898. </label>
  5899. `).join('');
  5900. }
  5901. async function submitSaveBridgeVLAN(e) {
  5902. e.preventDefault();
  5903. const id = document.getElementById('bridge-vlan-modal-id').value;
  5904. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  5905. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  5906. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  5907. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  5908. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  5909. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  5910. try {
  5911. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  5912. method: 'POST',
  5913. headers: { 'Content-Type': 'application/json' },
  5914. body: JSON.stringify({
  5915. id,
  5916. bridge,
  5917. vlan_ids: vlanIDs,
  5918. tagged,
  5919. untagged,
  5920. comment,
  5921. disabled
  5922. })
  5923. });
  5924. if (res.ok) {
  5925. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  5926. closeBridgeVlanModal();
  5927. loadBridge();
  5928. } else {
  5929. const err = await res.json();
  5930. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  5931. }
  5932. } catch (err) {
  5933. showToast('Error', err.message, 'error');
  5934. }
  5935. }
  5936. async function toggleBridgeVLANState(id, disabled) {
  5937. try {
  5938. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  5939. method: 'POST',
  5940. headers: { 'Content-Type': 'application/json' },
  5941. body: JSON.stringify({ disabled })
  5942. });
  5943. if (res.ok) loadBridge();
  5944. } catch (err) {
  5945. showToast('Error', err.message, 'error');
  5946. }
  5947. }
  5948. async function deleteBridgeVLAN(id) {
  5949. if (!confirm('Delete this bridge VLAN entry?')) return;
  5950. try {
  5951. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5952. if (res.ok) {
  5953. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  5954. loadBridge();
  5955. }
  5956. } catch (err) {
  5957. showToast('Error', err.message, 'error');
  5958. }
  5959. }
  5960. // ----------------- Hosts / MAC Table -----------------
  5961. async function loadBridgeHosts() {
  5962. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  5963. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  5964. try {
  5965. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  5966. const res = await fetch(url);
  5967. if (res.ok) {
  5968. state.bridgeHosts = await res.json();
  5969. renderBridgeHosts();
  5970. }
  5971. } catch (err) {
  5972. console.error('Failed to load bridge hosts:', err);
  5973. }
  5974. }
  5975. function renderBridgeHosts() {
  5976. const tbody = document.getElementById('bridge-hosts-table-body');
  5977. const empty = document.getElementById('bridge-empty-hosts');
  5978. const countBadge = document.getElementById('bridge-hosts-count-badge');
  5979. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  5980. if (!tbody) return;
  5981. tbody.innerHTML = '';
  5982. const hosts = (state.bridgeHosts || []).filter(h => {
  5983. if (!search) return true;
  5984. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  5985. });
  5986. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  5987. if (hosts.length === 0) {
  5988. empty?.classList.remove('hidden');
  5989. return;
  5990. }
  5991. empty?.classList.add('hidden');
  5992. hosts.forEach(h => {
  5993. const tr = document.createElement('tr');
  5994. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  5995. let flagBadges = '';
  5996. 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>';
  5997. 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>';
  5998. 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>';
  5999. tr.innerHTML = `
  6000. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  6001. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  6002. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  6003. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  6004. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  6005. <td class="py-2.5 px-3">${flagBadges}</td>
  6006. `;
  6007. tbody.appendChild(tr);
  6008. });
  6009. }
  6010. async function flushBridgeHosts() {
  6011. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  6012. if (!selBridge) {
  6013. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  6014. return;
  6015. }
  6016. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  6017. try {
  6018. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  6019. method: 'POST',
  6020. headers: { 'Content-Type': 'application/json' },
  6021. body: JSON.stringify({ bridge: selBridge })
  6022. });
  6023. if (res.ok) {
  6024. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  6025. loadBridgeHosts();
  6026. }
  6027. } catch (err) {
  6028. showToast('Error', err.message, 'error');
  6029. }
  6030. }
  6031. // ----------------- Helpers -----------------
  6032. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  6033. const sel = document.getElementById(selectId);
  6034. if (!sel) return;
  6035. const prevVal = currentVal || sel.value;
  6036. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  6037. (state.bridges || []).forEach(b => {
  6038. const opt = document.createElement('option');
  6039. opt.value = b.name;
  6040. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  6041. if (b.name === prevVal) opt.selected = true;
  6042. sel.appendChild(opt);
  6043. });
  6044. }
  6045. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  6046. const sel = document.getElementById(selectId);
  6047. if (!sel) return;
  6048. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  6049. // 1. Physical Interfaces
  6050. const grpPhys = document.createElement('optgroup');
  6051. grpPhys.label = 'Physical Interfaces';
  6052. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  6053. const opt = document.createElement('option');
  6054. opt.value = i.name;
  6055. opt.innerText = `${i.name} (${i.role || i.type})`;
  6056. if (i.name === currentVal) opt.selected = true;
  6057. grpPhys.appendChild(opt);
  6058. });
  6059. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  6060. // 2. VLAN Sub-interfaces
  6061. const grpVlans = document.createElement('optgroup');
  6062. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  6063. (state.vlans || []).forEach(v => {
  6064. const opt = document.createElement('option');
  6065. opt.value = v.name;
  6066. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  6067. if (v.name === currentVal) opt.selected = true;
  6068. grpVlans.appendChild(opt);
  6069. });
  6070. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  6071. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  6072. const grpEoip = document.createElement('optgroup');
  6073. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  6074. (state.eoipTunnels || []).forEach(t => {
  6075. const opt = document.createElement('option');
  6076. opt.value = t.name;
  6077. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  6078. if (t.name === currentVal) opt.selected = true;
  6079. grpEoip.appendChild(opt);
  6080. });
  6081. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  6082. }