app.js 298 KB

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