app.js 357 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435
  1. // Proxmox RouterOS Frontend Application Logic
  2. let state = {
  3. interfaces: [],
  4. vlans: [],
  5. systemStatus: null,
  6. vpnStatus: null,
  7. routes: [],
  8. activeTab: 'dashboard',
  9. fwSubTab: 'filter',
  10. bridgeSubTab: 'bridges',
  11. bridges: [],
  12. bridgePorts: [],
  13. bridgeVLANs: [],
  14. bridgeHosts: [],
  15. bridgeSummary: null,
  16. routesSubTab: 'routes',
  17. pppSubTab: 'secrets',
  18. eoipTunnels: [],
  19. pppSecrets: [],
  20. pppProfiles: [],
  21. pppActiveSessions: [],
  22. pppoeServer: null,
  23. pptpServer: null,
  24. l2tpServer: null,
  25. ipsecServer: null,
  26. ifaceFilter: 'all',
  27. currentModalIface: null,
  28. isPolling: true,
  29. expandedParents: new Set(['eth0']),
  30. pppoeData: null,
  31. wgData: null,
  32. ipsecData: null,
  33. l2tpData: null,
  34. pptpData: null,
  35. fwSummary: null,
  36. filterRules: [],
  37. natRules: [],
  38. mangleRules: [],
  39. addressLists: [],
  40. connections: [],
  41. policyRules: [],
  42. routingTables: [],
  43. routingFilters: [],
  44. filterChainSelected: 'all',
  45. activeToolsSubTab: 'ping',
  46. dhcpClients: [],
  47. dhcpSummary: null
  48. };
  49. const API_BASE = '/api';
  50. function escapeHtml(str) {
  51. if (str === null || str === undefined) return '';
  52. return String(str)
  53. .replace(/&/g, '&')
  54. .replace(/</g, '&lt;')
  55. .replace(/>/g, '&gt;')
  56. .replace(/"/g, '&quot;')
  57. .replace(/'/g, '&#039;');
  58. }
  59. // Initialize on page load
  60. document.addEventListener('DOMContentLoaded', () => {
  61. const hash = window.location.hash.replace('#', '') || 'dashboard';
  62. navigate(hash);
  63. fetchData();
  64. // Live polling every 2.5 seconds
  65. setInterval(() => {
  66. if (state.isPolling) {
  67. fetchData(false);
  68. }
  69. }, 2500);
  70. });
  71. // Navigation Handler
  72. function navigate(tabName) {
  73. if (tabName === 'dynamic-routing' || tabName === 'routing') {
  74. navigate('bgp');
  75. return;
  76. }
  77. if (tabName === 'vlans') {
  78. navigate('interfaces');
  79. return;
  80. }
  81. state.activeTab = tabName;
  82. window.location.hash = tabName;
  83. // Update nav links styling
  84. document.querySelectorAll('.nav-link').forEach(link => {
  85. link.className = 'nav-link flex items-center justify-between px-3 py-2 rounded-lg text-xs font-medium transition-all group text-slate-300 hover:bg-slate-800/80 hover:text-white';
  86. });
  87. const activeNav = document.getElementById(`nav-${tabName}`);
  88. if (activeNav) {
  89. activeNav.className = 'nav-link flex items-center justify-between px-3 py-2 rounded-lg text-xs font-medium transition-all group bg-brand-500/10 text-brand-400 border border-brand-500/20';
  90. }
  91. // Update page headers
  92. const titles = {
  93. dashboard: { title: 'Dashboard Overview', sub: 'Live router performance and network telemetry' },
  94. interfaces: { title: 'Network Interfaces', sub: 'Hierarchical view of physical interfaces and nested 802.1Q VLANs' },
  95. 'dhcp-client': { title: 'DHCP Client (/ip dhcp-client)', sub: 'RouterOS-style dynamic IPv4 lease configuration, default gateway & peer DNS on any interface' },
  96. bridge: { title: 'Bridge Interfaces', sub: 'MikroTik-style IEEE 802.1D / 802.1Q VLAN Filtering Bridge with RSTP & FDB' },
  97. vlans: { title: 'VLAN Virtual Networks', sub: 'IEEE 802.1Q sub-interface segmentation and routing' },
  98. firewall: { title: 'MikroTik Firewall', sub: 'Filter rules, NAT, Mangle, Address Lists & Active Connections tracking' },
  99. routes: { title: 'Routing & Policy', sub: 'Routing tables, static routes (DAS/DAC), and policy routing rules' },
  100. bgp: { title: 'BGP Routing (/routing bgp)', sub: 'FRRouting BGP peering sessions, advertised networks, and BGP routing table (RIB)' },
  101. ospf: { title: 'OSPF Routing (/routing ospf)', sub: 'FRRouting OSPFv2 link-state routing, dynamic neighbor adjacencies, and multi-area topology' },
  102. 'routing-filters': { title: 'Routing Filters (/routing filter)', sub: 'MikroTik-style route filter chains, prefix matching, BGP attributes & policy maps' },
  103. 'dynamic-routing': { title: 'BGP Routing (/routing bgp)', sub: 'FRRouting dynamic routing' },
  104. ppp: { title: 'PPP Servers & Secrets', sub: 'MikroTik RouterOS user accounts, IP pools and VPN server concentrators' },
  105. eoip: { title: 'EoIP Tunnels', sub: 'Ethernet over IP Layer 2 tunneling (MikroTik RouterOS style)' },
  106. pppoe: { title: 'PPPoE Client WAN', sub: 'Point-to-Point Protocol over Ethernet WAN access' },
  107. wireguard: { title: 'WireGuard Kernel VPN', sub: 'Modern ultra-fast cryptographic VPN tunnel manager' },
  108. ipsec: { title: 'IPSec (IKEv2) strongSwan', sub: 'Enterprise Site-to-Site & Roadwarrior IPSec controller' },
  109. l2tp: { title: 'L2TP VPN Client', sub: 'Layer 2 Tunneling Protocol via xl2tpd' },
  110. pptp: { title: 'PPTP VPN Client', sub: 'Point-to-Point Tunneling Protocol with MPPE-128 encryption' },
  111. tools: { title: 'Troubleshoot & Diagnostic Tools (/tool)', sub: 'RouterOS-style Ping, Traceroute, MTR Telemetry, DNS resolution, and TCP Port probing' },
  112. persistence: { title: 'Debian Configuration', sub: 'Native /etc/network/interfaces.d/ persistence manager' }
  113. };
  114. const header = titles[tabName] || titles.dashboard;
  115. const pTitle = document.getElementById('page-title');
  116. if (pTitle) pTitle.innerText = header.title;
  117. const pSub = document.getElementById('page-subtitle');
  118. if (pSub) pSub.innerText = header.sub;
  119. // Toggle sections dynamically for all section elements
  120. document.querySelectorAll('main section[id^="section-"]').forEach(el => {
  121. if (el.id === `section-${tabName}`) {
  122. el.classList.remove('hidden');
  123. } else {
  124. el.classList.add('hidden');
  125. }
  126. });
  127. if (tabName === 'bridge') loadBridge();
  128. if (tabName === 'firewall') loadFirewall();
  129. if (tabName === 'routes') loadRoutes();
  130. if (tabName === 'bgp') {
  131. loadDynamicRouting();
  132. switchBgpSubTab(state.activeBgpSubTab || 'bgp-peers');
  133. }
  134. if (tabName === 'ospf') {
  135. loadDynamicRouting();
  136. switchOspfSubTab(state.activeOspfSubTab || 'ospf-ifaces');
  137. }
  138. if (tabName === 'routing-filters') loadDynamicRouting();
  139. if (tabName === 'dynamic-routing') loadDynamicRouting();
  140. if (tabName === 'ppp') loadPPP();
  141. if (tabName === 'eoip') loadEoIP();
  142. if (tabName === 'persistence') loadDebianConfig();
  143. if (tabName === 'pppoe') loadPPPoE();
  144. if (tabName === 'wireguard') loadWireGuard();
  145. if (tabName === 'ipsec') loadIPSec();
  146. if (tabName === 'l2tp') loadL2TP();
  147. if (tabName === 'pptp') loadPPTP();
  148. if (tabName === 'tools') loadToolsView();
  149. if (tabName === 'dhcp-client') loadDHCPClients();
  150. }
  151. // Fetch all core system, network and VPN telemetry
  152. async function fetchData(isManual = false) {
  153. const spinner = document.getElementById('refresh-spinner');
  154. if (isManual && spinner) spinner.classList.add('animate-spin');
  155. try {
  156. const [statusRes, ifacesRes, vlansRes, vpnRes, fwRes, dynRes, brSummaryRes, dhcpSumRes, dhcpClientsRes] = await Promise.all([
  157. fetch(`${API_BASE}/system/status`),
  158. fetch(`${API_BASE}/interfaces`),
  159. fetch(`${API_BASE}/vlans`),
  160. fetch(`${API_BASE}/vpn/status`),
  161. fetch(`${API_BASE}/firewall/summary`),
  162. fetch(`${API_BASE}/routing/dynamic/summary`),
  163. fetch(`${API_BASE}/bridge/summary`),
  164. fetch(`${API_BASE}/dhcp/clients/summary`),
  165. fetch(`${API_BASE}/dhcp/clients`)
  166. ]);
  167. if (dhcpSumRes && dhcpSumRes.ok) {
  168. state.dhcpSummary = await dhcpSumRes.json();
  169. const bDhcp = document.getElementById('badge-dhcp-client-count');
  170. if (bDhcp) bDhcp.innerText = state.dhcpSummary?.total_clients || 0;
  171. }
  172. if (dhcpClientsRes && dhcpClientsRes.ok) {
  173. state.dhcpClients = await dhcpClientsRes.json();
  174. }
  175. if (brSummaryRes.ok) {
  176. state.bridgeSummary = await brSummaryRes.json();
  177. const bBridge = document.getElementById('badge-bridge-count');
  178. if (bBridge) bBridge.innerText = state.bridgeSummary?.bridges_count || 0;
  179. const sBr = document.getElementById('bridge-stat-bridges');
  180. if (sBr) sBr.innerText = state.bridgeSummary?.bridges_count || 0;
  181. const sPorts = document.getElementById('bridge-stat-ports');
  182. if (sPorts) sPorts.innerText = state.bridgeSummary?.ports_count || 0;
  183. const sHosts = document.getElementById('bridge-stat-hosts');
  184. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  185. }
  186. if (statusRes.ok) state.systemStatus = await statusRes.json();
  187. if (ifacesRes.ok) {
  188. const ifacesData = await ifacesRes.json();
  189. const rawIfaces = Array.isArray(ifacesData) ? ifacesData : [];
  190. state.interfaces = rawIfaces.filter(i => {
  191. if (!i.name) return false;
  192. if (i.name.startsWith('ep_')) return false;
  193. return !['gre0', 'gretap0', 'erspan0', 'sit0', 'tunl0', 'ip6tnl0', 'ip6gre0', 'ip6erspan0'].includes(i.name);
  194. });
  195. try { populateToolsInterfaces(); } catch (e) {}
  196. }
  197. if (vlansRes.ok) {
  198. const vlansData = await vlansRes.json();
  199. state.vlans = Array.isArray(vlansData) ? vlansData : [];
  200. }
  201. if (vpnRes.ok) state.vpnStatus = await vpnRes.json();
  202. if (fwRes && fwRes.ok) state.fwSummary = await fwRes.json();
  203. if (dynRes && dynRes.ok) state.dynSummary = await dynRes.json();
  204. updateSystemMetrics();
  205. updateBadges();
  206. if (state.activeTab === 'dashboard') renderDashboard();
  207. if (state.activeTab === 'interfaces') renderInterfacesList();
  208. if (state.activeTab === 'vlans') renderVlansList();
  209. if (state.activeTab === 'firewall') loadFirewall(false);
  210. if (state.activeTab === 'routes') loadRoutes(false);
  211. if (state.activeTab === 'dynamic-routing' || state.activeTab === 'bgp' || state.activeTab === 'ospf') loadDynamicRouting(false);
  212. if (state.activeTab === 'ppp') loadPPP(false);
  213. if (state.activeTab === 'eoip') loadEoIP(false);
  214. if (state.activeTab === 'pppoe') loadPPPoE(false);
  215. if (state.activeTab === 'wireguard') loadWireGuard(false);
  216. if (state.activeTab === 'ipsec') loadIPSec(false);
  217. if (state.activeTab === 'l2tp') loadL2TP(false);
  218. if (state.activeTab === 'pptp') loadPPTP(false);
  219. if (state.activeTab === 'dhcp-client') loadDHCPClients(false);
  220. } catch (err) {
  221. console.error('Failed to fetch router state:', err);
  222. } finally {
  223. if (isManual && spinner) {
  224. setTimeout(() => spinner.classList.remove('animate-spin'), 300);
  225. }
  226. }
  227. }
  228. // Update Top KPI and Sidebar Telemetry
  229. function updateSystemMetrics() {
  230. const s = state.systemStatus;
  231. const v = state.vpnStatus;
  232. if (!s) return;
  233. // Sidebar Host & Uptime
  234. const sideHost = document.getElementById('side-hostname');
  235. if (sideHost) sideHost.innerText = s.hostname || 'debian-lxc';
  236. const sideUp = document.getElementById('side-uptime');
  237. if (sideUp) sideUp.innerText = s.uptime_human || '0m';
  238. const sideGw = document.getElementById('side-gateway-ip');
  239. if (sideGw) sideGw.innerText = s.default_gateway ? `GW: ${s.default_gateway}` : 'GW: Isolated';
  240. // Compute CPU Metrics
  241. let cpuPct = 0;
  242. if (s.cpu_pct !== undefined) {
  243. cpuPct = s.cpu_pct;
  244. } else if (s.cpu_load && s.cpu_load.length > 0) {
  245. const cores = s.cpu_cores || 1;
  246. cpuPct = Math.min(100, Math.round((parseFloat(s.cpu_load[0]) / cores) * 100));
  247. }
  248. const cpuPctStr = `${cpuPct.toFixed(1)}%`;
  249. const cpuWidth = `${Math.max(3, Math.min(100, cpuPct))}%`;
  250. const loadStr = s.cpu_load ? s.cpu_load.join(', ') : '-';
  251. // Sidebar CPU
  252. const sideCpuVal = document.getElementById('side-cpu-val');
  253. if (sideCpuVal) sideCpuVal.innerText = cpuPctStr;
  254. const sideCpuBar = document.getElementById('side-cpu-bar');
  255. if (sideCpuBar) {
  256. sideCpuBar.style.width = cpuWidth;
  257. sideCpuBar.title = `Container: ${cpuPctStr} | Host Loadavg: ${loadStr} (${s.cpu_cores || 1} cores)`;
  258. }
  259. // Dashboard CPU Card
  260. const dashCpuVal = document.getElementById('dash-cpu-val');
  261. if (dashCpuVal) dashCpuVal.innerText = cpuPctStr;
  262. const dashCpuBar = document.getElementById('dash-cpu-bar');
  263. if (dashCpuBar) {
  264. dashCpuBar.style.width = cpuWidth;
  265. if (cpuPct > 85) {
  266. dashCpuBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  267. } else if (cpuPct > 65) {
  268. dashCpuBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  269. } else {
  270. dashCpuBar.className = 'h-full rounded-full bg-emerald-500 transition-all duration-500';
  271. }
  272. }
  273. const dashCpuCores = document.getElementById('dash-cpu-cores');
  274. if (dashCpuCores) dashCpuCores.innerText = `${s.cpu_cores || 1} Cores`;
  275. const dashCpuLoad = document.getElementById('dash-cpu-load');
  276. if (dashCpuLoad) dashCpuLoad.innerText = loadStr;
  277. const dashCpuStatus = document.getElementById('dash-cpu-status');
  278. if (dashCpuStatus) {
  279. if (cpuPct > 85) {
  280. dashCpuStatus.innerText = 'High';
  281. dashCpuStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  282. } else if (cpuPct > 65) {
  283. dashCpuStatus.innerText = 'Heavy';
  284. dashCpuStatus.className = 'text-[11px] font-semibold text-amber-400 uppercase px-2 py-0.5 rounded bg-amber-500/10';
  285. } else {
  286. dashCpuStatus.innerText = 'Normal';
  287. dashCpuStatus.className = 'text-[11px] font-semibold text-emerald-400 uppercase px-2 py-0.5 rounded bg-emerald-500/10';
  288. }
  289. }
  290. // Compute RAM Metrics
  291. const memPct = Math.round(s.mem_usage_pct || 0);
  292. const memPctStr = `${memPct}%`;
  293. const memWidth = `${Math.max(3, Math.min(100, memPct))}%`;
  294. const usedMB = s.mem_used_mb || 0;
  295. const totalMB = s.mem_total_mb || 0;
  296. const freeMB = totalMB > usedMB ? totalMB - usedMB : 0;
  297. function fmtMemMB(mb) {
  298. if (mb >= 1024) {
  299. return `${(mb / 1024).toFixed(1)} GB`;
  300. }
  301. return `${mb} MB`;
  302. }
  303. // Sidebar RAM
  304. const sideRamVal = document.getElementById('side-ram-val');
  305. if (sideRamVal) sideRamVal.innerText = memPctStr;
  306. const sideRamBar = document.getElementById('side-ram-bar');
  307. if (sideRamBar) sideRamBar.style.width = memWidth;
  308. // Dashboard RAM Card
  309. const dashRamVal = document.getElementById('dash-ram-val');
  310. if (dashRamVal) dashRamVal.innerText = memPctStr;
  311. const dashRamBar = document.getElementById('dash-ram-bar');
  312. if (dashRamBar) {
  313. dashRamBar.style.width = memWidth;
  314. if (memPct > 85) {
  315. dashRamBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  316. } else if (memPct > 70) {
  317. dashRamBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  318. } else {
  319. dashRamBar.className = 'h-full rounded-full bg-indigo-500 transition-all duration-500';
  320. }
  321. }
  322. const dashRamUsedTotal = document.getElementById('dash-ram-used-total');
  323. if (dashRamUsedTotal) {
  324. dashRamUsedTotal.innerText = `${fmtMemMB(usedMB)} / ${fmtMemMB(totalMB)}`;
  325. }
  326. const dashRamFree = document.getElementById('dash-ram-free');
  327. if (dashRamFree) {
  328. dashRamFree.innerText = fmtMemMB(freeMB);
  329. }
  330. const dashRamStatus = document.getElementById('dash-ram-status');
  331. if (dashRamStatus) {
  332. if (memPct > 85) {
  333. dashRamStatus.innerText = 'High';
  334. dashRamStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  335. } else {
  336. dashRamStatus.innerText = 'Active';
  337. dashRamStatus.className = 'text-[11px] font-semibold text-indigo-400 uppercase px-2 py-0.5 rounded bg-indigo-500/10';
  338. }
  339. }
  340. // Legacy Dashboard Stats (Safe checks)
  341. const elIfacesUp = document.getElementById('stat-ifaces-up');
  342. if (elIfacesUp) elIfacesUp.innerText = s.up_ifaces || 0;
  343. const elIfacesTot = document.getElementById('stat-ifaces-total');
  344. if (elIfacesTot) elIfacesTot.innerText = `${s.total_ifaces || 0} Total`;
  345. const elIfacesDown = document.getElementById('stat-ifaces-down');
  346. if (elIfacesDown) elIfacesDown.innerText = `${s.down_ifaces || 0} DOWN`;
  347. const elVlans = document.getElementById('stat-vlans-count');
  348. if (elVlans) elVlans.innerText = s.vlan_ifaces || 0;
  349. // VPN Status Indicators
  350. if (v) {
  351. const totalActive = v.total_active_tunnels || 0;
  352. const statVpnActive = document.getElementById('stat-vpn-active');
  353. if (statVpnActive) statVpnActive.innerText = totalActive;
  354. const tunnelsDot = document.getElementById('tunnels-dot');
  355. const tunnelsLabel = document.getElementById('tunnels-label');
  356. if (tunnelsDot && tunnelsLabel) {
  357. if (totalActive > 0) {
  358. tunnelsDot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  359. tunnelsLabel.innerText = `${totalActive} Active VPN Tunnel${totalActive > 1 ? 's' : ''}`;
  360. } else {
  361. tunnelsDot.className = 'w-2 h-2 rounded-full bg-slate-500';
  362. tunnelsLabel.innerText = '0 Active VPN Tunnels';
  363. }
  364. }
  365. setDotBadge('badge-pppoe-status', (v.active_pppoe || 0) > 0 || v.pppoe_connected);
  366. setDotBadge('badge-wg-status', (v.active_wireguard || 0) > 0 || v.wireguard_active);
  367. setDotBadge('badge-ipsec-status', (v.active_ipsec || 0) > 0 || v.ipsec_active);
  368. setDotBadge('badge-l2tp-status', (v.active_l2tp || 0) > 0 || v.l2tp_connected);
  369. setDotBadge('badge-pptp-status', (v.active_pptp || 0) > 0 || v.pptp_connected);
  370. }
  371. // Total Live Bandwidth Rate
  372. let totalRx = 0;
  373. let totalTx = 0;
  374. (state.interfaces || []).forEach(i => {
  375. if (i.rate) {
  376. totalRx += i.rate.rx_bytes_sec || 0;
  377. totalTx += i.rate.tx_bytes_sec || 0;
  378. }
  379. });
  380. document.getElementById('stat-traffic-rx').innerText = formatTraffic(totalRx);
  381. document.getElementById('stat-traffic-tx').innerText = formatTraffic(totalTx);
  382. }
  383. function setDotBadge(id, active) {
  384. const el = document.getElementById(id);
  385. if (!el) return;
  386. if (active) {
  387. el.className = 'w-2 h-2 rounded-full bg-emerald-400 shadow-sm shadow-emerald-400/80';
  388. } else {
  389. el.className = 'w-2 h-2 rounded-full bg-slate-600';
  390. }
  391. }
  392. function updateBadges() {
  393. const bIfaces = document.getElementById('badge-ifaces-count');
  394. if (bIfaces) bIfaces.innerText = (state.interfaces || []).length;
  395. const bVlans = document.getElementById('badge-vlans-count');
  396. if (bVlans) bVlans.innerText = (state.vlans || []).length;
  397. if (state.fwSummary) {
  398. const totalFwRules = (state.fwSummary.filter_rules_count || 0) + (state.fwSummary.nat_rules_count || 0) + (state.fwSummary.mangle_rules_count || 0);
  399. const badgeFw = document.getElementById('badge-firewall-count');
  400. if (badgeFw) badgeFw.innerText = totalFwRules;
  401. }
  402. if (state.vpnStatus) {
  403. const v = state.vpnStatus;
  404. const bEoIP = document.getElementById('badge-eoip-count');
  405. if (bEoIP) bEoIP.innerText = v.total_eoip || 0;
  406. const bPPPSess = document.getElementById('badge-ppp-sessions');
  407. if (bPPPSess) bPPPSess.innerText = v.total_ppp_sessions || 0;
  408. setDotBadge('badge-pppoe-status', v.active_pppoe > 0 || v.pppoe_server_running);
  409. setDotBadge('badge-wg-status', v.active_wireguard > 0);
  410. setDotBadge('badge-ipsec-status', v.active_ipsec > 0 || v.ipsec_server_running);
  411. setDotBadge('badge-l2tp-status', v.active_l2tp > 0 || v.l2tp_server_running);
  412. setDotBadge('badge-pptp-status', v.active_pptp > 0 || v.pptp_server_running);
  413. }
  414. if (state.dynSummary) {
  415. const d = state.dynSummary;
  416. setDotBadge('badge-bgp-dot', d.bgp_running);
  417. setDotBadge('badge-ospf-dot', d.ospf_running);
  418. const bBgp = document.getElementById('badge-bgp-count');
  419. if (bBgp) bBgp.innerText = (state.bgpPeers || []).length;
  420. const bOspf = document.getElementById('badge-ospf-count');
  421. if (bOspf) bOspf.innerText = (state.ospfInterfaces || []).length;
  422. const bFilters = document.getElementById('badge-filters-count');
  423. if (bFilters) bFilters.innerText = (state.routingFilters || []).length;
  424. }
  425. }
  426. // Render Dashboard View
  427. function renderDashboard() {
  428. const matrix = document.getElementById('port-matrix');
  429. matrix.innerHTML = '';
  430. (state.interfaces || []).forEach(iface => {
  431. const isUp = iface.state === 'UP';
  432. const isVlan = iface.is_vlan;
  433. const portCard = document.createElement('div');
  434. portCard.className = `p-3 rounded-xl border transition-all cursor-pointer select-none group ${
  435. isUp
  436. ? (isVlan ? 'bg-cyan-950/20 border-cyan-800/60 hover:border-cyan-500' : 'bg-slate-800/80 border-slate-700/80 hover:border-brand-500')
  437. : 'bg-slate-900/40 border-slate-800/60 opacity-60 hover:opacity-100 hover:border-slate-700'
  438. }`;
  439. portCard.onclick = () => openIfaceModal(iface.name);
  440. let statusPillClass = isUp ? 'bg-emerald-500 shadow-sm shadow-emerald-500/50' : 'bg-rose-500';
  441. if (isVlan) statusPillClass = isUp ? 'bg-cyan-400 shadow-sm shadow-cyan-400/50' : 'bg-rose-500';
  442. portCard.innerHTML = `
  443. <div class="flex items-center justify-between mb-2">
  444. <span class="font-bold text-xs font-mono text-white group-hover:text-brand-400 transition truncate">${iface.name}</span>
  445. <span class="w-2 h-2 rounded-full ${statusPillClass}"></span>
  446. </div>
  447. <div class="text-[11px] font-mono text-slate-300 truncate">${iface.ipv4 && iface.ipv4.length > 0 ? iface.ipv4[0] : (iface.mac || 'No IP')}</div>
  448. <div class="mt-2 flex items-center justify-between text-[10px] text-slate-400">
  449. <span class="uppercase tracking-wider font-semibold">${isVlan ? `VLAN ${iface.vlan_id}` : iface.type}</span>
  450. <span>${iface.rate?.rx_human || '0 B/s'}</span>
  451. </div>
  452. `;
  453. matrix.appendChild(portCard);
  454. });
  455. const ifaceTbody = document.getElementById('quick-interfaces-table');
  456. if (ifaceTbody) {
  457. ifaceTbody.innerHTML = '';
  458. (state.interfaces || []).forEach(i => {
  459. const isUp = i.state === 'UP';
  460. const tr = document.createElement('tr');
  461. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  462. tr.onclick = () => openIfaceModal(i.name);
  463. const rxStr = i.rate?.rx_human || '0 B/s';
  464. const txStr = i.rate?.tx_human || '0 B/s';
  465. tr.innerHTML = `
  466. <td class="py-2.5 font-bold text-white flex items-center gap-2">
  467. <span class="w-2 h-2 rounded-full ${isUp ? 'bg-emerald-400 shadow-sm shadow-emerald-400/50' : 'bg-rose-400'}"></span>
  468. <span>${i.name}</span>
  469. </td>
  470. <td class="py-2.5 text-slate-300 font-sans">
  471. <span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 font-medium">${i.role || i.type || 'Ethernet'}</span>
  472. </td>
  473. <td class="py-2.5 text-slate-400 text-[11px] font-mono">${i.mac || '-'}</td>
  474. <td class="py-2.5 text-slate-200 font-semibold">${i.ipv4 && i.ipv4.length > 0 ? i.ipv4.join(', ') : '<span class="text-slate-600 font-normal">Unassigned</span>'}</td>
  475. <td class="py-2.5 text-slate-300 text-[11px] font-mono">
  476. <span class="text-emerald-400">↓ ${rxStr}</span> <span class="text-slate-600">•</span> <span class="text-cyan-400">↑ ${txStr}</span>
  477. </td>
  478. <td class="py-2.5 text-right font-sans font-semibold">
  479. <span class="px-2 py-0.5 rounded text-[10px] ${isUp ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/20' : 'bg-rose-500/10 text-rose-400 border border-rose-500/20'}">${i.state}</span>
  480. </td>
  481. `;
  482. ifaceTbody.appendChild(tr);
  483. });
  484. }
  485. const vlanTbody = document.getElementById('quick-vlans-table');
  486. if (vlanTbody) {
  487. vlanTbody.innerHTML = '';
  488. }
  489. }
  490. // Expand / Collapse Handlers
  491. function toggleExpand(parentName) {
  492. if (state.expandedParents.has(parentName)) {
  493. state.expandedParents.delete(parentName);
  494. } else {
  495. state.expandedParents.add(parentName);
  496. }
  497. renderInterfacesList();
  498. }
  499. function expandAllIfaces(expand) {
  500. if (expand) {
  501. (state.interfaces || []).forEach(i => {
  502. if (!i.is_vlan) state.expandedParents.add(i.name);
  503. });
  504. } else {
  505. state.expandedParents.clear();
  506. }
  507. renderInterfacesList();
  508. }
  509. // Filter and Render Hierarchical Interfaces List
  510. function filterIfaces(filter) {
  511. state.ifaceFilter = filter;
  512. document.querySelectorAll('.filter-btn').forEach(btn => {
  513. 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';
  514. });
  515. const activeBtn = document.getElementById(`filter-${filter}`);
  516. if (activeBtn) {
  517. activeBtn.className = 'filter-btn px-3 py-1.5 rounded-lg text-xs font-medium bg-slate-800 text-white border border-slate-700';
  518. }
  519. renderInterfacesList();
  520. }
  521. function renderInterfacesList() {
  522. const tbody = document.getElementById('interfaces-tree-tbody');
  523. const emptyState = document.getElementById('interfaces-empty-state');
  524. const summary = document.getElementById('ifaces-list-summary');
  525. const query = (document.getElementById('iface-search')?.value || '').toLowerCase();
  526. tbody.innerHTML = '';
  527. const allIfaces = state.interfaces || [];
  528. const allVlans = state.vlans || [];
  529. const parentIfaces = allIfaces.filter(i => !i.is_vlan);
  530. const filteredParents = parentIfaces.filter(parent => {
  531. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  532. if (query) {
  533. const matchParent = parent.name.toLowerCase().includes(query) || (parent.role || '').toLowerCase().includes(query);
  534. const matchVlan = childVlans.some(v => v.name.toLowerCase().includes(query) || String(v.vlan_id).includes(query) || (v.description || '').toLowerCase().includes(query));
  535. if (!matchParent && !matchVlan) return false;
  536. }
  537. if (state.ifaceFilter === 'has_vlans') return childVlans.length > 0;
  538. if (state.ifaceFilter === 'physical') return parent.type !== 'loopback';
  539. if (state.ifaceFilter === 'up') return parent.state === 'UP';
  540. return true;
  541. });
  542. if (summary) {
  543. summary.innerText = `${parentIfaces.length} Physical/Parent Links • ${allVlans.length} Active VLANs`;
  544. }
  545. if (filteredParents.length === 0) {
  546. emptyState?.classList.remove('hidden');
  547. return;
  548. }
  549. emptyState?.classList.add('hidden');
  550. filteredParents.forEach(parent => {
  551. const isUp = parent.state === 'UP';
  552. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  553. const isExpanded = state.expandedParents.has(parent.name);
  554. const parentRow = document.createElement('tr');
  555. parentRow.className = `hover:bg-slate-800/50 transition border-b border-slate-800/80 ${isExpanded ? 'bg-slate-900/80' : ''}`;
  556. parentRow.innerHTML = `
  557. <td class="py-3 px-3 text-center">
  558. <button onclick="toggleExpand('${parent.name}')" title="${isExpanded ? 'Collapse VLANs' : 'Expand VLANs'}"
  559. class="w-6 h-6 rounded flex items-center justify-center hover:bg-slate-800 text-slate-400 hover:text-white transition">
  560. <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">
  561. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M9 5l7 7-7 7" />
  562. </svg>
  563. </button>
  564. </td>
  565. <td class="py-3 px-4">
  566. <div class="flex items-center space-x-2.5">
  567. <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">
  568. ${parent.type === 'loopback' ? 'LO' : 'NIC'}
  569. </div>
  570. <div>
  571. <div class="flex items-center gap-2">
  572. <span class="font-bold text-white text-sm cursor-pointer hover:text-cyan-400" onclick="toggleExpand('${parent.name}')">${parent.name}</span>
  573. ${childVlans.length > 0
  574. ? `<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>`
  575. : `<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>`
  576. }
  577. </div>
  578. <div class="text-[10px] text-slate-500 font-sans mt-0.5">${parent.type}</div>
  579. </div>
  580. </div>
  581. </td>
  582. <td class="py-3 px-4 font-sans">
  583. <div class="flex items-center gap-1.5">
  584. <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>
  585. <span class="text-xs text-slate-400 truncate max-w-[120px]">${parent.description || '-'}</span>
  586. </div>
  587. </td>
  588. <td class="py-3 px-4">
  589. ${parent.ipv4 && parent.ipv4.length > 0
  590. ? `<div class="text-white font-medium">${parent.ipv4[0]}</div>`
  591. : '<span class="text-slate-600 font-sans">Unassigned</span>'
  592. }
  593. ${(() => {
  594. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  595. if (!c) return '';
  596. const statusCls = c.status === 'bound' ? 'bg-amber-500/20 text-amber-300 border-amber-500/30' : (c.status === 'searching' ? 'bg-sky-500/20 text-sky-300 border-sky-500/30' : 'bg-slate-800 text-slate-400 border-slate-700');
  597. return `<div class="mt-1"><span class="px-1.5 py-0.5 rounded text-[10px] font-mono border ${statusCls} cursor-pointer hover:underline" onclick="navigate('dhcp-client')" title="DHCP Client: ${c.status.toUpperCase()} (${c.ip_address || 'requesting...'})">⚡ DHCP: ${c.status.toUpperCase()}</span></div>`;
  598. })()}
  599. </td>
  600. <td class="py-3 px-4 text-slate-400 text-[11px]">
  601. <div>${parent.mac || 'N/A'}</div>
  602. <div class="text-[10px] text-slate-500">MTU ${parent.mtu}</div>
  603. </td>
  604. <td class="py-3 px-4 text-[11px]">
  605. <div class="flex items-center space-x-2">
  606. <span class="text-emerald-400">↓ ${parent.rate?.rx_human || '0 B/s'}</span>
  607. <span class="text-cyan-400">↑ ${parent.rate?.tx_human || '0 B/s'}</span>
  608. </div>
  609. </td>
  610. <td class="py-3 px-4 font-sans">
  611. <button onclick="toggleInterfaceState('${parent.name}', '${isUp ? 'down' : 'up'}')"
  612. class="flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full transition ${
  613. 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'
  614. }" title="Click to toggle link status">
  615. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  616. <span>${parent.state}</span>
  617. </button>
  618. </td>
  619. <td class="py-3 px-4 text-right space-x-2 font-sans">
  620. ${(() => {
  621. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  622. if (c) {
  623. return `<button onclick="navigate('dhcp-client')" title="Manage DHCP Client (${c.status})" class="text-xs bg-amber-500/10 hover:bg-amber-500/20 text-amber-400 font-medium px-2.5 py-1 rounded-lg border border-amber-500/30 transition">⚡ DHCP</button>`;
  624. }
  625. return `<button onclick="openDHCPClientModalForIface('${parent.name}')" title="Add DHCP Client on ${parent.name}" class="text-xs bg-slate-800/80 hover:bg-slate-700 text-slate-300 hover:text-amber-400 font-medium px-2 py-1 rounded-lg border border-slate-700 transition">+ DHCP</button>`;
  626. })()}
  627. <button onclick="openVlanModal('${parent.name}')"
  628. 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">
  629. + Add VLAN
  630. </button>
  631. <button onclick="openIfaceModal('${parent.name}')"
  632. 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">
  633. Configure
  634. </button>
  635. </td>
  636. `;
  637. tbody.appendChild(parentRow);
  638. if (isExpanded) {
  639. const drawerRow = document.createElement('tr');
  640. drawerRow.className = 'bg-slate-950/80 border-b border-slate-800/90';
  641. const drawerCell = document.createElement('td');
  642. drawerCell.colSpan = 8;
  643. drawerCell.className = 'p-0';
  644. drawerCell.innerHTML = `
  645. <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">
  646. <div class="flex items-center justify-between mb-3">
  647. <div class="flex items-center space-x-3">
  648. <span class="font-bold text-xs text-white uppercase tracking-wider flex items-center gap-1.5 font-sans">
  649. <span>VLAN Sub-interfaces on <code class="text-cyan-300 lowercase">${parent.name}</code></span>
  650. </span>
  651. <span class="text-[11px] bg-cyan-950 text-cyan-400 px-2 py-0.5 rounded-full border border-cyan-800/60 font-mono">
  652. ${childVlans.length} Attached
  653. </span>
  654. </div>
  655. <button onclick="openVlanModal('${parent.name}')"
  656. 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">
  657. <span>+ Create VLAN on ${parent.name}</span>
  658. </button>
  659. </div>
  660. ${childVlans.length === 0 ? `
  661. <div class="p-6 text-center border border-dashed border-slate-800 rounded-xl bg-slate-900/40 font-sans">
  662. <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>
  663. <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">
  664. <span>+ Create Your First VLAN on ${parent.name}</span>
  665. </button>
  666. </div>
  667. ` : `
  668. <div class="overflow-x-auto rounded-lg border border-slate-800 bg-slate-900/90 shadow-inner">
  669. <table class="w-full text-left text-xs font-mono">
  670. <thead class="text-slate-400 bg-slate-950/70 border-b border-slate-800 uppercase tracking-wider text-[10px] font-sans">
  671. <tr>
  672. <th class="py-2.5 px-4">VLAN ID</th>
  673. <th class="py-2.5 px-4">Interface Device</th>
  674. <th class="py-2.5 px-4">Subnet Gateway</th>
  675. <th class="py-2.5 px-4">Role / Alias</th>
  676. <th class="py-2.5 px-4">MTU</th>
  677. <th class="py-2.5 px-4">Throughput</th>
  678. <th class="py-2.5 px-4">Status</th>
  679. <th class="py-2.5 px-4 text-right">Actions</th>
  680. </tr>
  681. </thead>
  682. <tbody class="divide-y divide-slate-800/70">
  683. ${childVlans.map(v => {
  684. const isVlanUp = v.state === 'UP';
  685. return `
  686. <tr class="hover:bg-slate-800/40 transition">
  687. <td class="py-2.5 px-4">
  688. <span class="px-2 py-0.5 rounded text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800 shadow-sm">
  689. VLAN ${v.vlan_id}
  690. </span>
  691. </td>
  692. <td class="py-2.5 px-4 font-bold text-white flex items-center gap-1.5">
  693. <span class="text-cyan-500">└─</span>
  694. <span>${v.name}</span>
  695. </td>
  696. <td class="py-2.5 px-4 text-emerald-400 font-medium">
  697. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  698. ${(() => {
  699. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  700. if (!c) return '';
  701. const statusCls = c.status === 'bound' ? 'bg-amber-500/20 text-amber-300 border-amber-500/30' : 'bg-slate-800 text-slate-400 border-slate-700';
  702. return `<div class="mt-0.5"><span class="px-1.5 py-0.2 rounded text-[9px] font-mono border ${statusCls} cursor-pointer hover:underline" onclick="navigate('dhcp-client')" title="DHCP Client: ${c.status.toUpperCase()}">⚡ DHCP: ${c.status.toUpperCase()}</span></div>`;
  703. })()}
  704. </td>
  705. <td class="py-2.5 px-4 font-sans text-slate-300">
  706. <span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 mr-1.5">${v.role || 'VLAN'}</span>
  707. <span class="text-slate-400 text-xs">${v.description || '-'}</span>
  708. </td>
  709. <td class="py-2.5 px-4 text-slate-400">${v.mtu}</td>
  710. <td class="py-2.5 px-4 text-[11px]">
  711. <span class="text-emerald-400">↓ ${v.rate?.rx_human || '0 B/s'}</span>
  712. <span class="text-cyan-400 ml-1.5">↑ ${v.rate?.tx_human || '0 B/s'}</span>
  713. </td>
  714. <td class="py-2.5 px-4 font-sans">
  715. <button onclick="toggleInterfaceState('${v.name}', '${isVlanUp ? 'down' : 'up'}')"
  716. class="flex items-center gap-1 text-[11px] font-semibold px-2 py-0.5 rounded-full ${
  717. 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'
  718. }">
  719. <span class="w-1.5 h-1.5 rounded-full ${isVlanUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  720. <span>${v.state}</span>
  721. </button>
  722. </td>
  723. <td class="py-2.5 px-4 text-right space-x-1.5 font-sans">
  724. ${(() => {
  725. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  726. if (c) {
  727. return `<button onclick="navigate('dhcp-client')" class="text-xs text-amber-400 hover:text-amber-300 px-2 py-0.5 rounded bg-amber-950/40 border border-amber-800/50">⚡ DHCP</button>`;
  728. }
  729. return `<button onclick="openDHCPClientModalForIface('${v.name}')" class="text-xs text-slate-400 hover:text-amber-400 px-1.5 py-0.5 rounded border border-slate-700">+ DHCP</button>`;
  730. })()}
  731. <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>
  732. <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>
  733. </td>
  734. </tr>
  735. `;
  736. }).join('')}
  737. </tbody>
  738. </table>
  739. </div>
  740. `}
  741. </div>
  742. `;
  743. drawerRow.appendChild(drawerCell);
  744. tbody.appendChild(drawerRow);
  745. }
  746. });
  747. }
  748. // Render VLANs Dedicated View
  749. function renderVlansList() {
  750. const tbody = document.getElementById('vlans-table-body');
  751. if (!tbody) return;
  752. const emptyState = document.getElementById('vlans-empty-state');
  753. const countBadge = document.getElementById('vlans-table-count');
  754. const query = (document.getElementById('vlan-search')?.value || '').toLowerCase();
  755. tbody.innerHTML = '';
  756. const allVlans = state.vlans || [];
  757. if (countBadge) countBadge.innerText = allVlans.length;
  758. const filtered = allVlans.filter(v => {
  759. if (!query) return true;
  760. return v.name.toLowerCase().includes(query) ||
  761. String(v.vlan_id).includes(query) ||
  762. (v.description || '').toLowerCase().includes(query) ||
  763. (v.ipv4 && v.ipv4.some(ip => ip.includes(query)));
  764. });
  765. if (allVlans.length === 0) {
  766. emptyState.classList.remove('hidden');
  767. return;
  768. }
  769. emptyState.classList.add('hidden');
  770. filtered.forEach(v => {
  771. const isUp = v.state === 'UP';
  772. const tr = document.createElement('tr');
  773. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  774. tr.innerHTML = `
  775. <td class="py-3 px-4">
  776. <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">
  777. VLAN ${v.vlan_id}
  778. </span>
  779. </td>
  780. <td class="py-3 px-4 font-bold text-white">${v.name}</td>
  781. <td class="py-3 px-4 text-slate-300">
  782. <span class="bg-slate-800 text-slate-200 px-2 py-0.5 rounded text-[11px]">${v.parent_name || 'eth0'}</span>
  783. </td>
  784. <td class="py-3 px-4 text-emerald-400 font-medium">
  785. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  786. </td>
  787. <td class="py-3 px-4 text-slate-300 font-sans">
  788. <span class="text-slate-400 text-xs">${v.description || v.role || '-'}</span>
  789. </td>
  790. <td class="py-3 px-4 text-slate-400">${v.mtu}</td>
  791. <td class="py-3 px-4 font-sans">
  792. <button onclick="toggleInterfaceState('${v.name}', '${isUp ? 'down' : 'up'}')"
  793. class="flex items-center gap-1.5 text-xs font-semibold px-2 py-0.5 rounded-full ${
  794. 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'
  795. }">
  796. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  797. <span>${v.state}</span>
  798. </button>
  799. </td>
  800. <td class="py-3 px-4 text-right space-x-2 font-sans">
  801. <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>
  802. <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>
  803. </td>
  804. `;
  805. tbody.appendChild(tr);
  806. });
  807. }
  808. // Toggle interface UP / DOWN
  809. async function toggleInterfaceState(name, newState) {
  810. try {
  811. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(name)}/state`, {
  812. method: 'POST',
  813. headers: { 'Content-Type': 'application/json' },
  814. body: JSON.stringify({ state: newState })
  815. });
  816. const data = await res.json();
  817. if (res.ok) {
  818. showToast('Interface Updated', `Interface ${name} is now ${newState.toUpperCase()}`, 'success');
  819. fetchData(false);
  820. } else {
  821. showToast('Error', data.message || 'Failed to toggle interface state', 'error');
  822. }
  823. } catch (err) {
  824. showToast('Error', err.message, 'error');
  825. }
  826. }
  827. // ---------------- MikroTik Flag & Utilities ----------------
  828. function renderMikroTikFlag(running, disabled) {
  829. if (running) {
  830. 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>`;
  831. }
  832. if (disabled) {
  833. 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>`;
  834. }
  835. 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>`;
  836. }
  837. function copyToClipboard(text, label = 'Text') {
  838. navigator.clipboard.writeText(text).then(() => {
  839. showToast('Copied', `${label} copied to clipboard`, 'success');
  840. }).catch(() => {
  841. prompt('Copy value:', text);
  842. });
  843. }
  844. // ======================== PPPoE Multi-Instance ========================
  845. async function loadPPPoE(populateInputs = true) {
  846. try {
  847. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`);
  848. const list = await res.json();
  849. state.pppoeList = Array.isArray(list) ? list : [];
  850. const badge = document.getElementById('pppoe-count-badge');
  851. if (badge) badge.innerText = `${state.pppoeList.length} Interface${state.pppoeList.length !== 1 ? 's' : ''}`;
  852. const tbody = document.getElementById('pppoe-table-body');
  853. const empty = document.getElementById('pppoe-empty');
  854. if (!tbody) return;
  855. tbody.innerHTML = '';
  856. if (state.pppoeList.length === 0) {
  857. if (empty) empty.classList.remove('hidden');
  858. } else {
  859. if (empty) empty.classList.add('hidden');
  860. state.pppoeList.forEach(inst => {
  861. const tr = document.createElement('tr');
  862. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  863. tr.innerHTML = `
  864. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  865. <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
  866. <td class="py-2.5 px-3 text-cyan-400 font-mono">${inst.interface}</td>
  867. <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
  868. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
  869. <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
  870. <td class="py-2.5 px-3 text-center">
  871. <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'}">
  872. ${inst.default_route ? 'Yes' : 'No'}
  873. </span>
  874. </td>
  875. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  876. ${inst.running ? `
  877. <button onclick="disconnectPPPoEInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  878. ` : `
  879. <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>
  880. `}
  881. <button onclick="togglePPPoEState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  882. ${inst.disabled ? 'Enable' : 'Disable'}
  883. </button>
  884. <button onclick="openEditPPPoEModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  885. <button onclick="deletePPPoEInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  886. </td>
  887. `;
  888. tbody.appendChild(tr);
  889. });
  890. }
  891. } catch (err) {
  892. console.error('Failed to load PPPoE:', err);
  893. }
  894. }
  895. function openAddPPPoEModal() {
  896. document.getElementById('pppoe-modal-title').innerText = 'Add PPPoE Client Interface';
  897. document.getElementById('pppoe-modal-edit-orig').value = '';
  898. document.getElementById('pppoe-modal-name').value = `pppoe-out${(state.pppoeList || []).length + 1}`;
  899. document.getElementById('pppoe-modal-name').readOnly = false;
  900. document.getElementById('pppoe-modal-user').value = '';
  901. document.getElementById('pppoe-modal-pass').value = '';
  902. document.getElementById('pppoe-modal-service').value = '';
  903. document.getElementById('pppoe-modal-mtu').value = '1492';
  904. document.getElementById('pppoe-modal-defroute').checked = true;
  905. document.getElementById('pppoe-modal-reconnect').checked = true;
  906. document.getElementById('pppoe-modal-disabled').checked = false;
  907. // Populate interfaces
  908. const sel = document.getElementById('pppoe-modal-iface');
  909. sel.innerHTML = '';
  910. (state.interfaces || []).forEach(i => {
  911. if (i.name === 'lo') return;
  912. const opt = document.createElement('option');
  913. opt.value = i.name;
  914. opt.innerText = `${i.name} (${i.role || i.type})`;
  915. sel.appendChild(opt);
  916. });
  917. document.getElementById('pppoe-modal').classList.remove('hidden');
  918. }
  919. function openEditPPPoEModal(name) {
  920. const inst = (state.pppoeList || []).find(i => i.name === name);
  921. if (!inst) return;
  922. document.getElementById('pppoe-modal-title').innerText = `Edit PPPoE Client: ${name}`;
  923. document.getElementById('pppoe-modal-edit-orig').value = name;
  924. document.getElementById('pppoe-modal-name').value = inst.name;
  925. document.getElementById('pppoe-modal-name').readOnly = true;
  926. document.getElementById('pppoe-modal-user').value = inst.username || '';
  927. document.getElementById('pppoe-modal-pass').value = inst.password || '';
  928. document.getElementById('pppoe-modal-service').value = inst.service_name || '';
  929. document.getElementById('pppoe-modal-mtu').value = inst.mtu || 1492;
  930. document.getElementById('pppoe-modal-defroute').checked = inst.default_route ?? true;
  931. document.getElementById('pppoe-modal-reconnect').checked = inst.auto_reconnect ?? true;
  932. document.getElementById('pppoe-modal-disabled').checked = !!inst.disabled;
  933. const sel = document.getElementById('pppoe-modal-iface');
  934. sel.innerHTML = '';
  935. (state.interfaces || []).forEach(i => {
  936. if (i.name === 'lo') return;
  937. const opt = document.createElement('option');
  938. opt.value = i.name;
  939. opt.innerText = `${i.name} (${i.role || i.type})`;
  940. if (i.name === inst.interface) opt.selected = true;
  941. sel.appendChild(opt);
  942. });
  943. document.getElementById('pppoe-modal').classList.remove('hidden');
  944. }
  945. function closePPPoEModal() {
  946. document.getElementById('pppoe-modal').classList.add('hidden');
  947. }
  948. async function submitSavePPPoE(e) {
  949. e.preventDefault();
  950. const name = document.getElementById('pppoe-modal-name').value.trim();
  951. const iface = document.getElementById('pppoe-modal-iface').value;
  952. const user = document.getElementById('pppoe-modal-user').value.trim();
  953. const pass = document.getElementById('pppoe-modal-pass').value;
  954. const service = document.getElementById('pppoe-modal-service').value.trim();
  955. const mtu = parseInt(document.getElementById('pppoe-modal-mtu').value, 10) || 1492;
  956. const defRoute = document.getElementById('pppoe-modal-defroute').checked;
  957. const reconnect = document.getElementById('pppoe-modal-reconnect').checked;
  958. const disabled = document.getElementById('pppoe-modal-disabled').checked;
  959. try {
  960. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`, {
  961. method: 'POST',
  962. headers: { 'Content-Type': 'application/json' },
  963. body: JSON.stringify({
  964. name,
  965. interface: iface,
  966. username: user,
  967. password: pass,
  968. service_name: service,
  969. mtu,
  970. default_route: defRoute,
  971. auto_reconnect: reconnect,
  972. disabled
  973. })
  974. });
  975. if (res.ok) {
  976. showToast('PPPoE Saved', `Configuration for ${name} saved`, 'success');
  977. closePPPoEModal();
  978. loadPPPoE(false);
  979. fetchData(false);
  980. } else {
  981. const err = await res.json();
  982. showToast('Error', err.message || 'Failed to save PPPoE', 'error');
  983. }
  984. } catch (err) {
  985. showToast('Error', err.message, 'error');
  986. }
  987. }
  988. async function connectPPPoEInstance(name) {
  989. try {
  990. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  991. if (res.ok) {
  992. showToast('Connecting', `Dialing ${name}...`, 'info');
  993. setTimeout(() => loadPPPoE(false), 2000);
  994. }
  995. } catch (err) {
  996. showToast('Error', err.message, 'error');
  997. }
  998. }
  999. async function disconnectPPPoEInstance(name) {
  1000. try {
  1001. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1002. if (res.ok) {
  1003. showToast('Disconnected', `${name} session terminated`, 'info');
  1004. setTimeout(() => loadPPPoE(false), 1000);
  1005. }
  1006. } catch (err) {
  1007. showToast('Error', err.message, 'error');
  1008. }
  1009. }
  1010. async function togglePPPoEState(name, enable) {
  1011. try {
  1012. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/state`, {
  1013. method: 'POST',
  1014. headers: { 'Content-Type': 'application/json' },
  1015. body: JSON.stringify({ enabled: enable })
  1016. });
  1017. if (res.ok) {
  1018. showToast(enable ? 'Enabled' : 'Disabled', `${name} is now ${enable ? 'enabled' : 'disabled'}`, 'info');
  1019. loadPPPoE(false);
  1020. }
  1021. } catch (err) {
  1022. showToast('Error', err.message, 'error');
  1023. }
  1024. }
  1025. async function deletePPPoEInstance(name) {
  1026. if (!confirm(`Are you sure you want to delete PPPoE client ${name}?`)) return;
  1027. try {
  1028. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1029. if (res.ok) {
  1030. showToast('Deleted', `PPPoE client ${name} removed`, 'success');
  1031. loadPPPoE(false);
  1032. fetchData(false);
  1033. }
  1034. } catch (err) {
  1035. showToast('Error', err.message, 'error');
  1036. }
  1037. }
  1038. // ======================== WireGuard Multi-Interface & Multi-Peer ========================
  1039. state.wgSubTab = 'ifaces';
  1040. function switchWGSubTab(tab) {
  1041. state.wgSubTab = tab;
  1042. const ifacesPanel = document.getElementById('wg-subtab-ifaces');
  1043. const peersPanel = document.getElementById('wg-subtab-peers');
  1044. const ifacesBtn = document.getElementById('wg-subtab-btn-ifaces');
  1045. const peersBtn = document.getElementById('wg-subtab-btn-peers');
  1046. if (tab === 'ifaces') {
  1047. ifacesPanel?.classList.remove('hidden');
  1048. peersPanel?.classList.add('hidden');
  1049. 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';
  1050. 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';
  1051. } else {
  1052. ifacesPanel?.classList.add('hidden');
  1053. peersPanel?.classList.remove('hidden');
  1054. 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';
  1055. 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';
  1056. renderWGPeers();
  1057. }
  1058. }
  1059. async function loadWireGuard(populateInputs = true) {
  1060. try {
  1061. const [ifacesRes, peersRes] = await Promise.all([
  1062. fetch(`${API_BASE}/vpn/wireguard/interfaces`),
  1063. fetch(`${API_BASE}/vpn/wireguard/peers`)
  1064. ]);
  1065. const ifaces = ifacesRes.ok ? await ifacesRes.json() : [];
  1066. const peers = peersRes.ok ? await peersRes.json() : [];
  1067. state.wgInterfaces = Array.isArray(ifaces) ? ifaces : [];
  1068. state.wgPeers = Array.isArray(peers) ? peers : [];
  1069. // Badges
  1070. const ifacesCountBadge = document.getElementById('wg-ifaces-count');
  1071. if (ifacesCountBadge) ifacesCountBadge.innerText = `${state.wgInterfaces.length} Interfaces`;
  1072. const peersCountBadge = document.getElementById('wg-peers-count');
  1073. if (peersCountBadge) peersCountBadge.innerText = `${state.wgPeers.length} Peers`;
  1074. const subTabIfaces = document.getElementById('wg-subtab-badge-ifaces');
  1075. if (subTabIfaces) subTabIfaces.innerText = state.wgInterfaces.length;
  1076. const subTabPeers = document.getElementById('wg-subtab-badge-peers');
  1077. if (subTabPeers) subTabPeers.innerText = state.wgPeers.length;
  1078. // Render Interfaces
  1079. const ifacesTbody = document.getElementById('wg-ifaces-table-body');
  1080. const ifacesEmpty = document.getElementById('wg-ifaces-empty');
  1081. if (ifacesTbody) {
  1082. ifacesTbody.innerHTML = '';
  1083. if (state.wgInterfaces.length === 0) {
  1084. if (ifacesEmpty) ifacesEmpty.classList.remove('hidden');
  1085. } else {
  1086. if (ifacesEmpty) ifacesEmpty.classList.add('hidden');
  1087. state.wgInterfaces.forEach(iface => {
  1088. const peersOnIface = state.wgPeers.filter(p => p.interface === iface.name).length;
  1089. const tr = document.createElement('tr');
  1090. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1091. tr.innerHTML = `
  1092. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(iface.running, iface.disabled)}</td>
  1093. <td class="py-2.5 px-3">
  1094. <div class="flex items-center gap-1.5">
  1095. <span class="font-bold text-white">${escapeHtml(iface.name)}</span>
  1096. ${iface.comment ? `<span class="text-[10px] text-slate-400 font-sans italic">(${escapeHtml(iface.comment)})</span>` : ''}
  1097. </div>
  1098. </td>
  1099. <td class="py-2.5 px-3 text-amber-400 font-mono">${iface.listen_port}</td>
  1100. <td class="py-2.5 px-3 text-emerald-400 font-mono">${iface.address || '<span class="text-slate-600 font-sans">--</span>'}</td>
  1101. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1102. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${iface.public_key}', 'Public Key')" title="Click to copy: ${iface.public_key}">
  1103. ${(iface.public_key || '').substring(0, 10)}... 📋
  1104. </span>
  1105. </td>
  1106. <td class="py-2.5 px-3 text-slate-400 font-mono">${iface.mtu || 1420}</td>
  1107. <td class="py-2.5 px-3 text-center">
  1108. <span class="px-2 py-0.5 rounded text-[10px] font-sans bg-slate-800 text-slate-300">${peersOnIface} peer${peersOnIface !== 1 ? 's' : ''}</span>
  1109. </td>
  1110. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  1111. ${iface.running ? `
  1112. <button onclick="stopWGInterface('${iface.name}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Stop</button>
  1113. ` : `
  1114. <button onclick="startWGInterface('${iface.name}')" class="text-xs bg-rose-600/30 hover:bg-rose-600/50 text-rose-300 px-2 py-0.5 rounded border border-rose-500/30 font-medium">Start</button>
  1115. `}
  1116. <button onclick="toggleWGInterfaceState('${iface.name}', ${iface.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white font-medium">
  1117. ${iface.disabled ? 'Enable' : 'Disable'}
  1118. </button>
  1119. <button onclick="openEditWGInterfaceModal('${iface.name}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1120. <button onclick="deleteWGInterface('${iface.name}')" class="text-xs text-slate-500 hover:text-rose-400 font-medium">Delete</button>
  1121. </td>
  1122. `;
  1123. ifacesTbody.appendChild(tr);
  1124. });
  1125. }
  1126. }
  1127. // Populate filter dropdown in peers tab
  1128. const filterSel = document.getElementById('wg-peers-filter-iface');
  1129. if (filterSel) {
  1130. const currentVal = filterSel.value;
  1131. filterSel.innerHTML = '<option value="">All Interfaces</option>';
  1132. state.wgInterfaces.forEach(i => {
  1133. const opt = document.createElement('option');
  1134. opt.value = i.name;
  1135. opt.innerText = i.name;
  1136. if (i.name === currentVal) opt.selected = true;
  1137. filterSel.appendChild(opt);
  1138. });
  1139. }
  1140. renderWGPeers();
  1141. } catch (err) {
  1142. console.error('Failed to load WireGuard:', err);
  1143. }
  1144. }
  1145. function renderWGPeers() {
  1146. const filterSel = document.getElementById('wg-peers-filter-iface');
  1147. const selectedIface = filterSel ? filterSel.value : '';
  1148. const tbody = document.getElementById('wg-peers-table-body');
  1149. const empty = document.getElementById('wg-peers-empty');
  1150. if (!tbody) return;
  1151. tbody.innerHTML = '';
  1152. const filtered = selectedIface ? state.wgPeers.filter(p => p.interface === selectedIface) : state.wgPeers;
  1153. if (filtered.length === 0) {
  1154. if (empty) empty.classList.remove('hidden');
  1155. } else {
  1156. if (empty) empty.classList.add('hidden');
  1157. filtered.forEach(p => {
  1158. const isOnline = p.latest_handshake && !p.latest_handshake.includes('Never');
  1159. const tr = document.createElement('tr');
  1160. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1161. tr.innerHTML = `
  1162. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isOnline, p.disabled)}</td>
  1163. <td class="py-2.5 px-3 font-mono font-bold text-rose-400">${escapeHtml(p.interface)}</td>
  1164. <td class="py-2.5 px-3 font-bold text-white font-sans">${escapeHtml(p.name || 'Unnamed')}</td>
  1165. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1166. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${p.public_key}', 'Peer Public Key')" title="${p.public_key}">
  1167. ${(p.public_key || '').substring(0, 10)}... 📋
  1168. </span>
  1169. </td>
  1170. <td class="py-2.5 px-3 text-emerald-400 font-mono font-semibold">${(p.allowed_ips || []).join(', ')}</td>
  1171. <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>
  1172. <td class="py-2.5 px-3 text-slate-300 font-sans">${p.latest_handshake || 'Never'}</td>
  1173. <td class="py-2.5 px-3 font-mono text-[11px]">
  1174. <span class="text-emerald-400">↓ ${p.transfer_rx_human || '0 B'}</span>
  1175. <span class="text-cyan-400 ml-1">↑ ${p.transfer_tx_human || '0 B'}</span>
  1176. </td>
  1177. <td class="py-2.5 px-3 text-right font-sans space-x-2 whitespace-nowrap">
  1178. <button onclick="toggleWGPeerState('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}', ${p.disabled ? 'true' : 'false'})" class="text-xs ${p.disabled ? 'text-emerald-400 hover:text-emerald-300' : 'text-slate-400 hover:text-white'} font-medium">
  1179. ${p.disabled ? 'Enable' : 'Disable'}
  1180. </button>
  1181. <button onclick="openEditWGPeerModal('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1182. <button onclick="openWGClientConfModal('${escapeHtml(p.interface)}', '${(p.allowed_ips || [])[0] || '10.10.0.2/32'}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold" title="Generate WireGuard Client Profile (.conf)">Config (.conf)</button>
  1183. <button onclick="deleteWGPeer('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Delete</button>
  1184. </td>
  1185. `;
  1186. tbody.appendChild(tr);
  1187. });
  1188. }
  1189. }
  1190. function openAddWGInterfaceModal() {
  1191. document.getElementById('wg-iface-modal-title').innerText = 'Add WireGuard Interface';
  1192. document.getElementById('wg-iface-modal-edit-orig').value = '';
  1193. const nameEl = document.getElementById('wg-iface-modal-name');
  1194. nameEl.value = `wg${(state.wgInterfaces || []).length}`;
  1195. nameEl.readOnly = false;
  1196. document.getElementById('wg-iface-modal-port').value = 51820 + (state.wgInterfaces || []).length;
  1197. document.getElementById('wg-iface-modal-addr').value = `10.${10 + (state.wgInterfaces || []).length}.0.1/24`;
  1198. document.getElementById('wg-iface-modal-mtu').value = '1420';
  1199. document.getElementById('wg-iface-modal-comment').value = '';
  1200. document.getElementById('wg-iface-modal-pubkey').value = '';
  1201. document.getElementById('wg-iface-modal-privkey').value = '';
  1202. document.getElementById('wg-iface-modal-disabled').checked = false;
  1203. generateWGInterfaceKeys();
  1204. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1205. }
  1206. function openEditWGInterfaceModal(name) {
  1207. const iface = (state.wgInterfaces || []).find(i => i.name === name);
  1208. if (!iface) return;
  1209. document.getElementById('wg-iface-modal-title').innerText = `Edit WireGuard Interface: ${name}`;
  1210. document.getElementById('wg-iface-modal-edit-orig').value = name;
  1211. const nameEl = document.getElementById('wg-iface-modal-name');
  1212. nameEl.value = iface.name;
  1213. nameEl.readOnly = false; // ALLOW RENAMING
  1214. document.getElementById('wg-iface-modal-port').value = iface.listen_port || 51820;
  1215. document.getElementById('wg-iface-modal-addr').value = iface.address || '';
  1216. document.getElementById('wg-iface-modal-mtu').value = iface.mtu || 1420;
  1217. document.getElementById('wg-iface-modal-comment').value = iface.comment || '';
  1218. document.getElementById('wg-iface-modal-pubkey').value = iface.public_key || '';
  1219. document.getElementById('wg-iface-modal-privkey').value = iface.private_key || '';
  1220. document.getElementById('wg-iface-modal-disabled').checked = !!iface.disabled;
  1221. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1222. }
  1223. function closeAddWGInterfaceModal() {
  1224. document.getElementById('wg-iface-modal').classList.add('hidden');
  1225. }
  1226. async function generateWGInterfaceKeys() {
  1227. try {
  1228. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1229. const keys = await res.json();
  1230. if (res.ok) {
  1231. document.getElementById('wg-iface-modal-privkey').value = keys.private_key;
  1232. document.getElementById('wg-iface-modal-pubkey').value = keys.public_key;
  1233. }
  1234. } catch (err) {
  1235. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1236. }
  1237. }
  1238. async function onWGInterfacePrivKeyInput() {
  1239. const privKey = document.getElementById('wg-iface-modal-privkey').value.trim();
  1240. if (!privKey) return;
  1241. try {
  1242. const res = await fetch(`${API_BASE}/vpn/wireguard/calc-pubkey`, {
  1243. method: 'POST',
  1244. headers: { 'Content-Type': 'application/json' },
  1245. body: JSON.stringify({ private_key: privKey })
  1246. });
  1247. if (res.ok) {
  1248. const data = await res.json();
  1249. if (data.public_key) {
  1250. document.getElementById('wg-iface-modal-pubkey').value = data.public_key;
  1251. }
  1252. }
  1253. } catch (err) {
  1254. // Ignore while typing
  1255. }
  1256. }
  1257. function toggleWGPrivKeyVisibility() {
  1258. const el = document.getElementById('wg-iface-modal-privkey');
  1259. const btn = document.getElementById('btn-toggle-wg-privkey');
  1260. if (el.type === 'password') {
  1261. el.type = 'text';
  1262. btn.innerText = '🙈 Hide';
  1263. } else {
  1264. el.type = 'password';
  1265. btn.innerText = '👁️ Show';
  1266. }
  1267. }
  1268. function copyWGInterfacePubKey() {
  1269. const pub = document.getElementById('wg-iface-modal-pubkey').value;
  1270. if (pub) copyToClipboard(pub, 'Interface Public Key');
  1271. }
  1272. async function submitSaveWGInterface(e) {
  1273. e.preventDefault();
  1274. const origName = document.getElementById('wg-iface-modal-edit-orig').value.trim();
  1275. const name = document.getElementById('wg-iface-modal-name').value.trim();
  1276. const port = parseInt(document.getElementById('wg-iface-modal-port').value, 10) || 51820;
  1277. const addr = document.getElementById('wg-iface-modal-addr').value.trim();
  1278. const mtu = parseInt(document.getElementById('wg-iface-modal-mtu').value, 10) || 1420;
  1279. const comment = document.getElementById('wg-iface-modal-comment').value.trim();
  1280. const pub = document.getElementById('wg-iface-modal-pubkey').value.trim();
  1281. const priv = document.getElementById('wg-iface-modal-privkey').value.trim();
  1282. const disabled = document.getElementById('wg-iface-modal-disabled').checked;
  1283. try {
  1284. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces`, {
  1285. method: 'POST',
  1286. headers: { 'Content-Type': 'application/json' },
  1287. body: JSON.stringify({
  1288. orig_name: origName,
  1289. name,
  1290. listen_port: port,
  1291. address: addr,
  1292. mtu,
  1293. comment,
  1294. public_key: pub,
  1295. private_key: priv,
  1296. disabled
  1297. })
  1298. });
  1299. const data = await res.json();
  1300. if (res.ok) {
  1301. showToast('WireGuard Saved', `Interface ${name} configured successfully`, 'success');
  1302. closeAddWGInterfaceModal();
  1303. loadWireGuard(false);
  1304. fetchData(false);
  1305. } else {
  1306. showToast('Error', data.error || 'Failed to save interface', 'error');
  1307. }
  1308. } catch (err) {
  1309. showToast('Error', err.message, 'error');
  1310. }
  1311. }
  1312. async function startWGInterface(name) {
  1313. try {
  1314. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1315. if (res.ok) {
  1316. showToast('Interface UP', `Started WireGuard interface ${name}`, 'success');
  1317. loadWireGuard(false);
  1318. fetchData(false);
  1319. }
  1320. } catch (err) {
  1321. showToast('Error', err.message, 'error');
  1322. }
  1323. }
  1324. async function stopWGInterface(name) {
  1325. try {
  1326. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1327. if (res.ok) {
  1328. showToast('Interface DOWN', `Stopped WireGuard interface ${name}`, 'info');
  1329. loadWireGuard(false);
  1330. fetchData(false);
  1331. }
  1332. } catch (err) {
  1333. showToast('Error', err.message, 'error');
  1334. }
  1335. }
  1336. async function toggleWGInterfaceState(name, enable) {
  1337. try {
  1338. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/state`, {
  1339. method: 'POST',
  1340. headers: { 'Content-Type': 'application/json' },
  1341. body: JSON.stringify({ enabled: enable })
  1342. });
  1343. if (res.ok) {
  1344. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1345. loadWireGuard(false);
  1346. fetchData(false);
  1347. }
  1348. } catch (err) {
  1349. showToast('Error', err.message, 'error');
  1350. }
  1351. }
  1352. async function deleteWGInterface(name) {
  1353. if (!confirm(`Are you sure you want to delete WireGuard interface ${name}? All associated peers will also be removed.`)) return;
  1354. try {
  1355. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1356. if (res.ok) {
  1357. showToast('Deleted', `Interface ${name} removed`, 'success');
  1358. loadWireGuard(false);
  1359. fetchData(false);
  1360. }
  1361. } catch (err) {
  1362. showToast('Error', err.message, 'error');
  1363. }
  1364. }
  1365. function populateWGPeerIfaceSelect(selectedIface = '') {
  1366. const sel = document.getElementById('wg-peer-modal-iface');
  1367. if (!sel) return;
  1368. sel.innerHTML = '';
  1369. (state.wgInterfaces || []).forEach(i => {
  1370. const opt = document.createElement('option');
  1371. opt.value = i.name;
  1372. opt.innerText = `${i.name} (${i.address || 'No IP'})`;
  1373. if (i.name === selectedIface) opt.selected = true;
  1374. sel.appendChild(opt);
  1375. });
  1376. }
  1377. function openAddWGPeerModal() {
  1378. if ((state.wgInterfaces || []).length === 0) {
  1379. showToast('No Interfaces', 'Please add a WireGuard interface first before adding peers', 'warning');
  1380. openAddWGInterfaceModal();
  1381. return;
  1382. }
  1383. document.getElementById('wg-peer-modal-title').innerText = 'Add WireGuard Peer';
  1384. document.getElementById('wg-peer-modal-edit-orig-iface').value = '';
  1385. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = '';
  1386. populateWGPeerIfaceSelect();
  1387. document.getElementById('wg-peer-modal-name').value = '';
  1388. document.getElementById('wg-peer-modal-pubkey').value = '';
  1389. document.getElementById('wg-peer-modal-allowedips').value = '10.10.0.2/32';
  1390. document.getElementById('wg-peer-modal-endpoint').value = '';
  1391. document.getElementById('wg-peer-modal-port').value = '';
  1392. document.getElementById('wg-peer-modal-keepalive').value = '25';
  1393. document.getElementById('wg-peer-modal-preshared').value = '';
  1394. document.getElementById('wg-peer-modal-disabled').checked = false;
  1395. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  1396. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  1397. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1398. }
  1399. function openEditWGPeerModal(ifaceName, pubKey) {
  1400. const peer = (state.wgPeers || []).find(p => p.interface === ifaceName && p.public_key === pubKey);
  1401. if (!peer) {
  1402. showToast('Not Found', 'Peer not found', 'warning');
  1403. return;
  1404. }
  1405. document.getElementById('wg-peer-modal-title').innerText = `Edit WireGuard Peer (${peer.name || ifaceName})`;
  1406. document.getElementById('wg-peer-modal-edit-orig-iface').value = peer.interface;
  1407. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = peer.public_key;
  1408. populateWGPeerIfaceSelect(peer.interface);
  1409. document.getElementById('wg-peer-modal-name').value = peer.name || '';
  1410. document.getElementById('wg-peer-modal-pubkey').value = peer.public_key || '';
  1411. document.getElementById('wg-peer-modal-allowedips').value = (peer.allowed_ips || []).join(', ');
  1412. document.getElementById('wg-peer-modal-endpoint').value = peer.endpoint_address || '';
  1413. document.getElementById('wg-peer-modal-port').value = peer.endpoint_port || '';
  1414. document.getElementById('wg-peer-modal-keepalive').value = peer.persistent_keepalive ?? 25;
  1415. document.getElementById('wg-peer-modal-preshared').value = peer.preshared_key || '';
  1416. document.getElementById('wg-peer-modal-disabled').checked = !!peer.disabled;
  1417. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  1418. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  1419. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1420. }
  1421. function closeAddWGPeerModal() {
  1422. document.getElementById('wg-peer-modal').classList.add('hidden');
  1423. }
  1424. async function generatePeerKeypairHelper() {
  1425. try {
  1426. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1427. const keys = await res.json();
  1428. if (res.ok) {
  1429. document.getElementById('wg-peer-modal-pubkey').value = keys.public_key;
  1430. document.getElementById('wg-peer-gen-privkey').value = keys.private_key;
  1431. document.getElementById('wg-peer-gen-key-box').classList.remove('hidden');
  1432. checkWGPeerKeyValidity();
  1433. showToast('Keypair Generated', 'Public key inserted and client private key ready to copy', 'info');
  1434. }
  1435. } catch (err) {
  1436. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1437. }
  1438. }
  1439. function copyGeneratedPeerPrivKey() {
  1440. const priv = document.getElementById('wg-peer-gen-privkey').value;
  1441. if (priv) copyToClipboard(priv, 'Client Private Key');
  1442. }
  1443. async function generatePeerPSK() {
  1444. try {
  1445. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1446. const keys = await res.json();
  1447. if (res.ok && keys.private_key) {
  1448. document.getElementById('wg-peer-modal-preshared').value = keys.private_key;
  1449. showToast('PSK Generated', 'Generated 256-bit preshared key', 'info');
  1450. }
  1451. } catch (err) {
  1452. showToast('Error', err.message, 'error');
  1453. }
  1454. }
  1455. function checkWGPeerKeyValidity() {
  1456. const ifaceName = document.getElementById('wg-peer-modal-iface').value;
  1457. const peerPubKey = document.getElementById('wg-peer-modal-pubkey').value.trim();
  1458. const warningEl = document.getElementById('wg-peer-key-warning');
  1459. if (!warningEl) return;
  1460. const targetIface = (state.wgInterfaces || []).find(i => i.name === ifaceName);
  1461. if (targetIface && targetIface.public_key && peerPubKey && targetIface.public_key === peerPubKey) {
  1462. warningEl.classList.remove('hidden');
  1463. } else {
  1464. warningEl.classList.add('hidden');
  1465. }
  1466. }
  1467. async function submitSaveWGPeer(e) {
  1468. e.preventDefault();
  1469. const origIface = document.getElementById('wg-peer-modal-edit-orig-iface').value.trim();
  1470. const origPubKey = document.getElementById('wg-peer-modal-edit-orig-pubkey').value.trim();
  1471. const iface = document.getElementById('wg-peer-modal-iface').value;
  1472. const name = document.getElementById('wg-peer-modal-name').value.trim();
  1473. const pub = document.getElementById('wg-peer-modal-pubkey').value.trim();
  1474. const allowed = document.getElementById('wg-peer-modal-allowedips').value
  1475. .split(',')
  1476. .map(s => s.trim())
  1477. .filter(s => s.length > 0);
  1478. const epHost = document.getElementById('wg-peer-modal-endpoint').value.trim();
  1479. const epPort = parseInt(document.getElementById('wg-peer-modal-port').value, 10) || 0;
  1480. const keepalive = parseInt(document.getElementById('wg-peer-modal-keepalive').value, 10) || 0;
  1481. const psk = document.getElementById('wg-peer-modal-preshared').value.trim();
  1482. const disabled = document.getElementById('wg-peer-modal-disabled').checked;
  1483. // Validation
  1484. const targetIface = (state.wgInterfaces || []).find(i => i.name === iface);
  1485. if (targetIface && targetIface.public_key === pub) {
  1486. showToast('Invalid Peer Key', 'Peer public key cannot be the same as the interface public key!', 'error');
  1487. return;
  1488. }
  1489. try {
  1490. const res = await fetch(`${API_BASE}/vpn/wireguard/peers`, {
  1491. method: 'POST',
  1492. headers: { 'Content-Type': 'application/json' },
  1493. body: JSON.stringify({
  1494. orig_interface: origIface,
  1495. orig_public_key: origPubKey,
  1496. interface: iface,
  1497. name,
  1498. public_key: pub,
  1499. allowed_ips: allowed,
  1500. endpoint_address: epHost,
  1501. endpoint_port: epPort,
  1502. persistent_keepalive: keepalive,
  1503. preshared_key: psk,
  1504. disabled
  1505. })
  1506. });
  1507. const data = await res.json();
  1508. if (res.ok) {
  1509. showToast('Peer Saved', `Peer ${name} saved on ${iface}`, 'success');
  1510. closeAddWGPeerModal();
  1511. loadWireGuard(false);
  1512. } else {
  1513. showToast('Error', data.error || 'Failed to save peer', 'error');
  1514. }
  1515. } catch (err) {
  1516. showToast('Error', err.message, 'error');
  1517. }
  1518. }
  1519. async function toggleWGPeerState(iface, pubkey, enable) {
  1520. try {
  1521. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/state`, {
  1522. method: 'POST',
  1523. headers: { 'Content-Type': 'application/json' },
  1524. body: JSON.stringify({ interface: iface, public_key: pubkey, enabled: enable })
  1525. });
  1526. const data = await res.json();
  1527. if (res.ok) {
  1528. showToast(enable ? 'Peer Enabled' : 'Peer Disabled', `Peer state updated on ${iface}`, 'info');
  1529. loadWireGuard(false);
  1530. } else {
  1531. showToast('Error', data.error || 'Failed to update peer state', 'error');
  1532. }
  1533. } catch (err) {
  1534. showToast('Error', err.message, 'error');
  1535. }
  1536. }
  1537. async function deleteWGPeer(iface, pubkey) {
  1538. if (!confirm(`Are you sure you want to remove peer from ${iface}?`)) return;
  1539. try {
  1540. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/delete`, {
  1541. method: 'POST',
  1542. headers: { 'Content-Type': 'application/json' },
  1543. body: JSON.stringify({ interface: iface, public_key: pubkey })
  1544. });
  1545. const data = await res.json();
  1546. if (res.ok) {
  1547. showToast('Peer Deleted', 'WireGuard peer removed', 'success');
  1548. loadWireGuard(false);
  1549. } else {
  1550. showToast('Error', data.error || 'Failed to remove peer', 'error');
  1551. }
  1552. } catch (err) {
  1553. showToast('Error', err.message, 'error');
  1554. }
  1555. }
  1556. // ======================== IPSec Multi-Tunnel ========================
  1557. async function loadIPSec(populateInputs = true) {
  1558. try {
  1559. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`);
  1560. const list = await res.json();
  1561. state.ipsecTunnels = Array.isArray(list) ? list : [];
  1562. const activeCount = state.ipsecTunnels.filter(t => t.running || t.status === 'ESTABLISHED').length;
  1563. const badge = document.getElementById('ipsec-sas-badge');
  1564. if (badge) badge.innerText = `${activeCount} Active SAs`;
  1565. const tbody = document.getElementById('ipsec-table-body');
  1566. const empty = document.getElementById('ipsec-empty');
  1567. if (!tbody) return;
  1568. tbody.innerHTML = '';
  1569. if (state.ipsecTunnels.length === 0) {
  1570. if (empty) empty.classList.remove('hidden');
  1571. } else {
  1572. if (empty) empty.classList.add('hidden');
  1573. state.ipsecTunnels.forEach(c => {
  1574. const isEstablished = c.running || c.status === 'ESTABLISHED';
  1575. const tr = document.createElement('tr');
  1576. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1577. tr.innerHTML = `
  1578. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isEstablished, c.disabled)}</td>
  1579. <td class="py-2.5 px-4 font-bold text-white">${c.name}</td>
  1580. <td class="py-2.5 px-4 text-emerald-400 font-mono">${c.local_subnet || '-'}</td>
  1581. <td class="py-2.5 px-4 text-slate-300 font-mono">${c.remote_addrs || '-'}</td>
  1582. <td class="py-2.5 px-4 text-cyan-400 font-mono">${c.remote_subnet || '-'}</td>
  1583. <td class="py-2.5 px-4 font-sans">
  1584. <span class="px-2 py-0.5 rounded-full text-[10px] font-semibold ${
  1585. isEstablished ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30' : 'bg-slate-800 text-slate-400'
  1586. }">${c.status || (isEstablished ? 'ESTABLISHED' : 'DISCONNECTED')}</span>
  1587. </td>
  1588. <td class="py-2.5 px-4 text-right space-x-2 font-sans">
  1589. ${isEstablished ? `
  1590. <button onclick="stopIPSecTunnel('${c.name}')" class="text-xs text-rose-400 hover:text-rose-300">Terminate</button>
  1591. ` : `
  1592. <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>
  1593. `}
  1594. <button onclick="toggleIPSecState('${c.name}', ${c.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1595. ${c.disabled ? 'Enable' : 'Disable'}
  1596. </button>
  1597. <button onclick="openEditIPSecModal('${c.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1598. <button onclick="deleteIPSecConn('${c.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1599. </td>
  1600. `;
  1601. tbody.appendChild(tr);
  1602. });
  1603. }
  1604. } catch (err) {
  1605. console.error('Failed to load IPSec:', err);
  1606. }
  1607. }
  1608. function openAddIPSecModal() {
  1609. document.getElementById('ipsec-modal-title').innerText = 'Configure IPSec IKEv2 Tunnel';
  1610. document.getElementById('ipsec-modal-name').value = `ipsec-${(state.ipsecTunnels || []).length + 1}`;
  1611. document.getElementById('ipsec-modal-name').readOnly = false;
  1612. document.getElementById('ipsec-modal-localts').value = '192.168.10.0/24';
  1613. document.getElementById('ipsec-modal-remotets').value = '192.168.20.0/24';
  1614. document.getElementById('ipsec-modal-remotegw').value = '';
  1615. document.getElementById('ipsec-modal-psk').value = '';
  1616. document.getElementById('ipsec-modal-ikeprop').value = 'aes256-sha256-modp2048,default';
  1617. document.getElementById('ipsec-modal-espprop').value = 'aes256-sha256-modp2048,default';
  1618. document.getElementById('ipsec-modal-autostart').checked = true;
  1619. document.getElementById('ipsec-modal-disabled').checked = false;
  1620. document.getElementById('ipsec-modal').classList.remove('hidden');
  1621. }
  1622. function openEditIPSecModal(name) {
  1623. const conn = (state.ipsecTunnels || []).find(c => c.name === name);
  1624. if (!conn) return;
  1625. document.getElementById('ipsec-modal-title').innerText = `Edit IPSec Tunnel: ${name}`;
  1626. document.getElementById('ipsec-modal-name').value = conn.name;
  1627. document.getElementById('ipsec-modal-name').readOnly = true;
  1628. document.getElementById('ipsec-modal-localts').value = conn.local_subnet || '';
  1629. document.getElementById('ipsec-modal-remotets').value = conn.remote_subnet || '';
  1630. document.getElementById('ipsec-modal-remotegw').value = conn.remote_addrs || '';
  1631. document.getElementById('ipsec-modal-psk').value = conn.preshared_key || '';
  1632. document.getElementById('ipsec-modal-ikeprop').value = conn.ike_proposals || 'aes256-sha256-modp2048,default';
  1633. document.getElementById('ipsec-modal-espprop').value = conn.esp_proposals || 'aes256-sha256-modp2048,default';
  1634. document.getElementById('ipsec-modal-autostart').checked = conn.auto_start ?? true;
  1635. document.getElementById('ipsec-modal-disabled').checked = !!conn.disabled;
  1636. document.getElementById('ipsec-modal').classList.remove('hidden');
  1637. }
  1638. function closeAddIPSecModal() {
  1639. document.getElementById('ipsec-modal').classList.add('hidden');
  1640. }
  1641. async function submitSaveIPSec(e) {
  1642. e.preventDefault();
  1643. const name = document.getElementById('ipsec-modal-name').value.trim();
  1644. const localts = document.getElementById('ipsec-modal-localts').value.trim();
  1645. const remotets = document.getElementById('ipsec-modal-remotets').value.trim();
  1646. const remotegw = document.getElementById('ipsec-modal-remotegw').value.trim();
  1647. const psk = document.getElementById('ipsec-modal-psk').value;
  1648. const ike = document.getElementById('ipsec-modal-ikeprop').value.trim();
  1649. const esp = document.getElementById('ipsec-modal-espprop').value.trim();
  1650. const autostart = document.getElementById('ipsec-modal-autostart').checked;
  1651. const disabled = document.getElementById('ipsec-modal-disabled').checked;
  1652. try {
  1653. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`, {
  1654. method: 'POST',
  1655. headers: { 'Content-Type': 'application/json' },
  1656. body: JSON.stringify({
  1657. name,
  1658. local_addrs: '%any',
  1659. remote_addrs: remotegw,
  1660. local_subnet: localts,
  1661. remote_subnet: remotets,
  1662. preshared_key: psk,
  1663. ike_proposals: ike,
  1664. esp_proposals: esp,
  1665. auto_start: autostart,
  1666. disabled
  1667. })
  1668. });
  1669. if (res.ok) {
  1670. showToast('IPSec Saved', `Tunnel ${name} configured`, 'success');
  1671. closeAddIPSecModal();
  1672. loadIPSec(false);
  1673. fetchData(false);
  1674. }
  1675. } catch (err) {
  1676. showToast('Error', err.message, 'error');
  1677. }
  1678. }
  1679. async function startIPSecTunnel(name) {
  1680. try {
  1681. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1682. if (res.ok) {
  1683. showToast('Initiating Tunnel', `Attempting SA handshake for ${name}...`, 'info');
  1684. setTimeout(() => loadIPSec(false), 2000);
  1685. }
  1686. } catch (err) {
  1687. showToast('Error', err.message, 'error');
  1688. }
  1689. }
  1690. async function stopIPSecTunnel(name) {
  1691. try {
  1692. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1693. if (res.ok) {
  1694. showToast('Terminated', `IPSec SA for ${name} closed`, 'info');
  1695. loadIPSec(false);
  1696. }
  1697. } catch (err) {
  1698. showToast('Error', err.message, 'error');
  1699. }
  1700. }
  1701. async function toggleIPSecState(name, enable) {
  1702. try {
  1703. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/state`, {
  1704. method: 'POST',
  1705. headers: { 'Content-Type': 'application/json' },
  1706. body: JSON.stringify({ enabled: enable })
  1707. });
  1708. if (res.ok) {
  1709. showToast(enable ? 'Enabled' : 'Disabled', `IPSec tunnel ${name} updated`, 'info');
  1710. loadIPSec(false);
  1711. }
  1712. } catch (err) {
  1713. showToast('Error', err.message, 'error');
  1714. }
  1715. }
  1716. async function deleteIPSecConn(name) {
  1717. if (!confirm(`Are you sure you want to delete IPSec tunnel ${name}?`)) return;
  1718. try {
  1719. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1720. if (res.ok) {
  1721. showToast('Deleted', `IPSec connection ${name} removed`, 'success');
  1722. loadIPSec(false);
  1723. fetchData(false);
  1724. }
  1725. } catch (err) {
  1726. showToast('Error', err.message, 'error');
  1727. }
  1728. }
  1729. // ======================== L2TP Multi-Instance ========================
  1730. async function loadL2TP(populateInputs = true) {
  1731. try {
  1732. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`);
  1733. const list = await res.json();
  1734. state.l2tpList = Array.isArray(list) ? list : [];
  1735. const badge = document.getElementById('l2tp-count-badge');
  1736. if (badge) badge.innerText = `${state.l2tpList.length} Client${state.l2tpList.length !== 1 ? 's' : ''}`;
  1737. const tbody = document.getElementById('l2tp-table-body');
  1738. const empty = document.getElementById('l2tp-empty');
  1739. if (!tbody) return;
  1740. tbody.innerHTML = '';
  1741. if (state.l2tpList.length === 0) {
  1742. if (empty) empty.classList.remove('hidden');
  1743. } else {
  1744. if (empty) empty.classList.add('hidden');
  1745. state.l2tpList.forEach(inst => {
  1746. const tr = document.createElement('tr');
  1747. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1748. tr.innerHTML = `
  1749. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1750. <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
  1751. <td class="py-2.5 px-3 text-cyan-400 font-mono">${inst.connect_to}</td>
  1752. <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
  1753. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
  1754. <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
  1755. <td class="py-2.5 px-3 text-center">
  1756. <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'}">
  1757. ${inst.default_route ? 'Yes' : 'No'}
  1758. </span>
  1759. </td>
  1760. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1761. ${inst.running ? `
  1762. <button onclick="disconnectL2TPInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1763. ` : `
  1764. <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>
  1765. `}
  1766. <button onclick="toggleL2TPState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1767. ${inst.disabled ? 'Enable' : 'Disable'}
  1768. </button>
  1769. <button onclick="openEditL2TPModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1770. <button onclick="deleteL2TPInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1771. </td>
  1772. `;
  1773. tbody.appendChild(tr);
  1774. });
  1775. }
  1776. } catch (err) {
  1777. console.error('Failed to load L2TP:', err);
  1778. }
  1779. }
  1780. function openAddL2TPModal() {
  1781. document.getElementById('l2tp-modal-title').innerText = 'Add L2TP Client Interface';
  1782. document.getElementById('l2tp-modal-name').value = `l2tp-out${(state.l2tpList || []).length + 1}`;
  1783. document.getElementById('l2tp-modal-name').readOnly = false;
  1784. document.getElementById('l2tp-modal-server').value = '';
  1785. document.getElementById('l2tp-modal-user').value = '';
  1786. document.getElementById('l2tp-modal-pass').value = '';
  1787. document.getElementById('l2tp-modal-ipsec').value = '';
  1788. document.getElementById('l2tp-modal-defroute').checked = true;
  1789. document.getElementById('l2tp-modal-disabled').checked = false;
  1790. document.getElementById('l2tp-modal').classList.remove('hidden');
  1791. }
  1792. function openEditL2TPModal(name) {
  1793. const inst = (state.l2tpList || []).find(i => i.name === name);
  1794. if (!inst) return;
  1795. document.getElementById('l2tp-modal-title').innerText = `Edit L2TP Client: ${name}`;
  1796. document.getElementById('l2tp-modal-name').value = inst.name;
  1797. document.getElementById('l2tp-modal-name').readOnly = true;
  1798. document.getElementById('l2tp-modal-server').value = inst.connect_to || '';
  1799. document.getElementById('l2tp-modal-user').value = inst.username || '';
  1800. document.getElementById('l2tp-modal-pass').value = inst.password || '';
  1801. document.getElementById('l2tp-modal-ipsec').value = inst.ipsec_secret || '';
  1802. document.getElementById('l2tp-modal-defroute').checked = inst.default_route ?? true;
  1803. document.getElementById('l2tp-modal-disabled').checked = !!inst.disabled;
  1804. document.getElementById('l2tp-modal').classList.remove('hidden');
  1805. }
  1806. function closeL2TPModal() {
  1807. document.getElementById('l2tp-modal').classList.add('hidden');
  1808. }
  1809. async function submitSaveL2TP(e) {
  1810. e.preventDefault();
  1811. const name = document.getElementById('l2tp-modal-name').value.trim();
  1812. const server = document.getElementById('l2tp-modal-server').value.trim();
  1813. const user = document.getElementById('l2tp-modal-user').value.trim();
  1814. const pass = document.getElementById('l2tp-modal-pass').value;
  1815. const ipsec = document.getElementById('l2tp-modal-ipsec').value;
  1816. const defRoute = document.getElementById('l2tp-modal-defroute').checked;
  1817. const disabled = document.getElementById('l2tp-modal-disabled').checked;
  1818. try {
  1819. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`, {
  1820. method: 'POST',
  1821. headers: { 'Content-Type': 'application/json' },
  1822. body: JSON.stringify({
  1823. name,
  1824. connect_to: server,
  1825. username: user,
  1826. password: pass,
  1827. ipsec_secret: ipsec,
  1828. default_route: defRoute,
  1829. disabled
  1830. })
  1831. });
  1832. if (res.ok) {
  1833. showToast('L2TP Saved', `Client ${name} configuration saved`, 'success');
  1834. closeL2TPModal();
  1835. loadL2TP(false);
  1836. fetchData(false);
  1837. }
  1838. } catch (err) {
  1839. showToast('Error', err.message, 'error');
  1840. }
  1841. }
  1842. async function connectL2TPInstance(name) {
  1843. try {
  1844. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1845. if (res.ok) {
  1846. showToast('Connecting', `Dialing L2TP ${name}...`, 'info');
  1847. setTimeout(() => loadL2TP(false), 2000);
  1848. }
  1849. } catch (err) {
  1850. showToast('Error', err.message, 'error');
  1851. }
  1852. }
  1853. async function disconnectL2TPInstance(name) {
  1854. try {
  1855. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1856. if (res.ok) {
  1857. showToast('Disconnected', `L2TP tunnel ${name} terminated`, 'info');
  1858. loadL2TP(false);
  1859. }
  1860. } catch (err) {
  1861. showToast('Error', err.message, 'error');
  1862. }
  1863. }
  1864. async function toggleL2TPState(name, enable) {
  1865. try {
  1866. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/state`, {
  1867. method: 'POST',
  1868. headers: { 'Content-Type': 'application/json' },
  1869. body: JSON.stringify({ enabled: enable })
  1870. });
  1871. if (res.ok) {
  1872. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1873. loadL2TP(false);
  1874. }
  1875. } catch (err) {
  1876. showToast('Error', err.message, 'error');
  1877. }
  1878. }
  1879. async function deleteL2TPInstance(name) {
  1880. if (!confirm(`Are you sure you want to delete L2TP client ${name}?`)) return;
  1881. try {
  1882. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1883. if (res.ok) {
  1884. showToast('Deleted', `L2TP client ${name} removed`, 'success');
  1885. loadL2TP(false);
  1886. fetchData(false);
  1887. }
  1888. } catch (err) {
  1889. showToast('Error', err.message, 'error');
  1890. }
  1891. }
  1892. // ======================== PPTP Multi-Instance ========================
  1893. async function loadPPTP(populateInputs = true) {
  1894. try {
  1895. const res = await fetch(`${API_BASE}/vpn/pptp/clients`);
  1896. const list = await res.json();
  1897. state.pptpList = Array.isArray(list) ? list : [];
  1898. const badge = document.getElementById('pptp-count-badge');
  1899. if (badge) badge.innerText = `${state.pptpList.length} Client${state.pptpList.length !== 1 ? 's' : ''}`;
  1900. const tbody = document.getElementById('pptp-table-body');
  1901. const empty = document.getElementById('pptp-empty');
  1902. if (!tbody) return;
  1903. tbody.innerHTML = '';
  1904. if (state.pptpList.length === 0) {
  1905. if (empty) empty.classList.remove('hidden');
  1906. } else {
  1907. if (empty) empty.classList.add('hidden');
  1908. state.pptpList.forEach(inst => {
  1909. const tr = document.createElement('tr');
  1910. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1911. tr.innerHTML = `
  1912. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1913. <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
  1914. <td class="py-2.5 px-3 text-purple-400 font-mono">${inst.connect_to}</td>
  1915. <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
  1916. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
  1917. <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
  1918. <td class="py-2.5 px-3 text-center">
  1919. <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'}">
  1920. ${inst.require_mppe ? 'MPPE-128' : 'None'}
  1921. </span>
  1922. </td>
  1923. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1924. ${inst.running ? `
  1925. <button onclick="disconnectPPTPInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1926. ` : `
  1927. <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>
  1928. `}
  1929. <button onclick="togglePPTPState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1930. ${inst.disabled ? 'Enable' : 'Disable'}
  1931. </button>
  1932. <button onclick="openEditPPTPModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1933. <button onclick="deletePPTPInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1934. </td>
  1935. `;
  1936. tbody.appendChild(tr);
  1937. });
  1938. }
  1939. } catch (err) {
  1940. console.error('Failed to load PPTP:', err);
  1941. }
  1942. }
  1943. function openAddPPTPModal() {
  1944. document.getElementById('pptp-modal-title').innerText = 'Add PPTP Client Interface';
  1945. document.getElementById('pptp-modal-name').value = `pptp-out${(state.pptpList || []).length + 1}`;
  1946. document.getElementById('pptp-modal-name').readOnly = false;
  1947. document.getElementById('pptp-modal-server').value = '';
  1948. document.getElementById('pptp-modal-user').value = '';
  1949. document.getElementById('pptp-modal-pass').value = '';
  1950. document.getElementById('pptp-modal-mppe').checked = true;
  1951. document.getElementById('pptp-modal-defroute').checked = true;
  1952. document.getElementById('pptp-modal-disabled').checked = false;
  1953. document.getElementById('pptp-modal').classList.remove('hidden');
  1954. }
  1955. function openEditPPTPModal(name) {
  1956. const inst = (state.pptpList || []).find(i => i.name === name);
  1957. if (!inst) return;
  1958. document.getElementById('pptp-modal-title').innerText = `Edit PPTP Client: ${name}`;
  1959. document.getElementById('pptp-modal-name').value = inst.name;
  1960. document.getElementById('pptp-modal-name').readOnly = true;
  1961. document.getElementById('pptp-modal-server').value = inst.connect_to || '';
  1962. document.getElementById('pptp-modal-user').value = inst.username || '';
  1963. document.getElementById('pptp-modal-pass').value = inst.password || '';
  1964. document.getElementById('pptp-modal-mppe').checked = inst.require_mppe ?? true;
  1965. document.getElementById('pptp-modal-defroute').checked = inst.default_route ?? true;
  1966. document.getElementById('pptp-modal-disabled').checked = !!inst.disabled;
  1967. document.getElementById('pptp-modal').classList.remove('hidden');
  1968. }
  1969. function closePPTPModal() {
  1970. document.getElementById('pptp-modal').classList.add('hidden');
  1971. }
  1972. async function submitSavePPTP(e) {
  1973. e.preventDefault();
  1974. const name = document.getElementById('pptp-modal-name').value.trim();
  1975. const server = document.getElementById('pptp-modal-server').value.trim();
  1976. const user = document.getElementById('pptp-modal-user').value.trim();
  1977. const pass = document.getElementById('pptp-modal-pass').value;
  1978. const mppe = document.getElementById('pptp-modal-mppe').checked;
  1979. const defRoute = document.getElementById('pptp-modal-defroute').checked;
  1980. const disabled = document.getElementById('pptp-modal-disabled').checked;
  1981. try {
  1982. const res = await fetch(`${API_BASE}/vpn/pptp/clients`, {
  1983. method: 'POST',
  1984. headers: { 'Content-Type': 'application/json' },
  1985. body: JSON.stringify({
  1986. name,
  1987. connect_to: server,
  1988. username: user,
  1989. password: pass,
  1990. require_mppe: mppe,
  1991. default_route: defRoute,
  1992. auto_reconnect: true,
  1993. disabled
  1994. })
  1995. });
  1996. if (res.ok) {
  1997. showToast('PPTP Saved', `Client ${name} configuration saved`, 'success');
  1998. closePPTPModal();
  1999. loadPPTP(false);
  2000. fetchData(false);
  2001. }
  2002. } catch (err) {
  2003. showToast('Error', err.message, 'error');
  2004. }
  2005. }
  2006. async function connectPPTPInstance(name) {
  2007. try {
  2008. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2009. if (res.ok) {
  2010. showToast('Connecting', `Dialing PPTP ${name}...`, 'info');
  2011. setTimeout(() => loadPPTP(false), 2000);
  2012. }
  2013. } catch (err) {
  2014. showToast('Error', err.message, 'error');
  2015. }
  2016. }
  2017. async function disconnectPPTPInstance(name) {
  2018. try {
  2019. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2020. if (res.ok) {
  2021. showToast('Disconnected', `PPTP tunnel ${name} terminated`, 'info');
  2022. loadPPTP(false);
  2023. }
  2024. } catch (err) {
  2025. showToast('Error', err.message, 'error');
  2026. }
  2027. }
  2028. async function togglePPTPState(name, enable) {
  2029. try {
  2030. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/state`, {
  2031. method: 'POST',
  2032. headers: { 'Content-Type': 'application/json' },
  2033. body: JSON.stringify({ enabled: enable })
  2034. });
  2035. if (res.ok) {
  2036. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2037. loadPPTP(false);
  2038. }
  2039. } catch (err) {
  2040. showToast('Error', err.message, 'error');
  2041. }
  2042. }
  2043. async function deletePPTPInstance(name) {
  2044. if (!confirm(`Are you sure you want to delete PPTP client ${name}?`)) return;
  2045. try {
  2046. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2047. if (res.ok) {
  2048. showToast('Deleted', `PPTP client ${name} removed`, 'success');
  2049. loadPPTP(false);
  2050. fetchData(false);
  2051. }
  2052. } catch (err) {
  2053. showToast('Error', err.message, 'error');
  2054. }
  2055. }
  2056. // ---------------- Modal & Helper Functions ----------------
  2057. function openVlanModal(defaultParent = '') {
  2058. const select = document.getElementById('vlan-parent');
  2059. select.innerHTML = '';
  2060. const allIfaces = state.interfaces || [];
  2061. const eligible = allIfaces.filter(i => !i.is_vlan && i.name !== 'lo');
  2062. if (eligible.length === 0) {
  2063. allIfaces.forEach(i => eligible.push(i));
  2064. }
  2065. eligible.forEach(i => {
  2066. const opt = document.createElement('option');
  2067. opt.value = i.name;
  2068. opt.innerText = `${i.name} (${i.role || 'Interface'} - ${i.state})`;
  2069. if (i.name === defaultParent) opt.selected = true;
  2070. select.appendChild(opt);
  2071. });
  2072. document.getElementById('vlan-id').value = '';
  2073. document.getElementById('vlan-name').value = '';
  2074. document.getElementById('vlan-ip').value = '';
  2075. document.getElementById('vlan-desc').value = '';
  2076. autoSuggestVlanName();
  2077. document.getElementById('vlan-modal').classList.remove('hidden');
  2078. }
  2079. function closeVlanModal() {
  2080. document.getElementById('vlan-modal').classList.add('hidden');
  2081. }
  2082. function autoSuggestVlanName() {
  2083. const parent = document.getElementById('vlan-parent').value;
  2084. const id = document.getElementById('vlan-id').value;
  2085. const nameInput = document.getElementById('vlan-name');
  2086. if (parent && id) nameInput.placeholder = `${parent}.${id}`;
  2087. }
  2088. function setSubnetPreset(cidr) {
  2089. const ipInput = document.getElementById('vlan-ip');
  2090. const id = document.getElementById('vlan-id').value || '10';
  2091. ipInput.value = `192.168.${id}.1${cidr}`;
  2092. }
  2093. async function submitCreateVlan(e) {
  2094. e.preventDefault();
  2095. const btn = document.getElementById('vlan-submit-btn');
  2096. btn.disabled = true;
  2097. btn.innerText = 'Creating...';
  2098. const parent = document.getElementById('vlan-parent').value;
  2099. const id = parseInt(document.getElementById('vlan-id').value, 10);
  2100. const name = document.getElementById('vlan-name').value.trim();
  2101. const ip = document.getElementById('vlan-ip').value.trim();
  2102. const role = document.getElementById('vlan-role').value;
  2103. const desc = document.getElementById('vlan-desc').value.trim();
  2104. try {
  2105. const res = await fetch(`${API_BASE}/vlans`, {
  2106. method: 'POST',
  2107. headers: { 'Content-Type': 'application/json' },
  2108. body: JSON.stringify({
  2109. parent_name: parent,
  2110. vlan_id: id,
  2111. name: name,
  2112. ip_address: ip,
  2113. role: role,
  2114. description: desc,
  2115. mtu: 1500,
  2116. auto_up: true
  2117. })
  2118. });
  2119. const data = await res.json();
  2120. if (res.ok) {
  2121. showToast('VLAN Created', `Created ${data.name} (VLAN ${data.vlan_id})`, 'success');
  2122. state.expandedParents.add(parent);
  2123. closeVlanModal();
  2124. await fetchData(true);
  2125. if (state.activeTab !== 'interfaces') navigate('interfaces');
  2126. } else {
  2127. showToast('Creation Failed', data.message || 'Failed to create VLAN', 'error');
  2128. }
  2129. } catch (err) {
  2130. showToast('Error', err.message, 'error');
  2131. } finally {
  2132. btn.disabled = false;
  2133. btn.innerText = 'Create VLAN';
  2134. }
  2135. }
  2136. async function confirmDeleteVlan(name) {
  2137. if (!confirm(`Delete VLAN interface ${name}?`)) return;
  2138. try {
  2139. const res = await fetch(`${API_BASE}/vlans/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2140. if (res.ok) {
  2141. showToast('VLAN Deleted', `Interface ${name} removed`, 'success');
  2142. closeIfaceModal();
  2143. fetchData(true);
  2144. }
  2145. } catch (err) {
  2146. showToast('Error', err.message, 'error');
  2147. }
  2148. }
  2149. function openIfaceModal(name) {
  2150. const iface = (state.interfaces || []).find(i => i.name === name);
  2151. if (!iface) return;
  2152. state.currentModalIface = iface.name;
  2153. document.getElementById('modal-iface-name').innerText = iface.name;
  2154. document.getElementById('modal-iface-badge').innerText = iface.is_vlan ? `VLAN ${iface.vlan_id}` : iface.type;
  2155. document.getElementById('modal-iface-mtu').value = iface.mtu;
  2156. document.getElementById('modal-iface-role').value = iface.role || 'LAN';
  2157. document.getElementById('modal-iface-desc').value = iface.description || '';
  2158. const delBtn = document.getElementById('modal-delete-vlan-btn');
  2159. if (iface.is_vlan) {
  2160. delBtn.classList.remove('hidden');
  2161. } else {
  2162. delBtn.classList.add('hidden');
  2163. }
  2164. renderModalIPs(iface);
  2165. document.getElementById('iface-modal').classList.remove('hidden');
  2166. }
  2167. function renderModalIPs(iface) {
  2168. const container = document.getElementById('modal-ip-list');
  2169. container.innerHTML = '';
  2170. const addrs = [...(iface.ipv4 || []), ...(iface.ipv6 || [])];
  2171. if (addrs.length === 0) {
  2172. container.innerHTML = `<span class="text-slate-500 text-xs font-sans">No IP addresses currently bound</span>`;
  2173. return;
  2174. }
  2175. addrs.forEach(addr => {
  2176. const row = document.createElement('div');
  2177. row.className = 'flex items-center justify-between p-2 rounded bg-slate-900 border border-slate-800';
  2178. row.innerHTML = `
  2179. <span class="text-white">${addr}</span>
  2180. <button onclick="removeInterfaceIP('${addr}')" class="text-[11px] text-rose-400 hover:text-rose-300 font-sans">Remove</button>
  2181. `;
  2182. container.appendChild(row);
  2183. });
  2184. }
  2185. function closeIfaceModal() {
  2186. document.getElementById('iface-modal').classList.add('hidden');
  2187. state.currentModalIface = null;
  2188. }
  2189. async function setIfaceState(name, newState) {
  2190. await toggleInterfaceState(name, newState);
  2191. const updated = (state.interfaces || []).find(i => i.name === name);
  2192. if (updated) openIfaceModal(name);
  2193. }
  2194. async function applyMTU() {
  2195. const mtu = parseInt(document.getElementById('modal-iface-mtu').value, 10);
  2196. try {
  2197. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/mtu`, {
  2198. method: 'POST',
  2199. headers: { 'Content-Type': 'application/json' },
  2200. body: JSON.stringify({ mtu })
  2201. });
  2202. if (res.ok) {
  2203. showToast('MTU Applied', `Set MTU to ${mtu} on ${state.currentModalIface}`, 'success');
  2204. fetchData(false);
  2205. }
  2206. } catch (err) {
  2207. showToast('Error', err.message, 'error');
  2208. }
  2209. }
  2210. async function addInterfaceIP() {
  2211. const ip = document.getElementById('modal-new-ip').value.trim();
  2212. if (!ip) return;
  2213. try {
  2214. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  2215. method: 'POST',
  2216. headers: { 'Content-Type': 'application/json' },
  2217. body: JSON.stringify({ ip })
  2218. });
  2219. if (res.ok) {
  2220. showToast('IP Added', `Bound ${ip} to ${state.currentModalIface}`, 'success');
  2221. document.getElementById('modal-new-ip').value = '';
  2222. await fetchData(false);
  2223. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  2224. if (iface) renderModalIPs(iface);
  2225. } else {
  2226. const err = await res.json();
  2227. showToast('Error', err.error || err.message || 'Failed to add IP address', 'error');
  2228. }
  2229. } catch (err) {
  2230. showToast('Error', err.message, 'error');
  2231. }
  2232. }
  2233. async function removeInterfaceIP(ip) {
  2234. if (!confirm(`Remove IP ${ip}?`)) return;
  2235. try {
  2236. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  2237. method: 'DELETE',
  2238. headers: { 'Content-Type': 'application/json' },
  2239. body: JSON.stringify({ ip })
  2240. });
  2241. if (res.ok) {
  2242. showToast('IP Removed', `Removed ${ip}`, 'success');
  2243. await fetchData(false);
  2244. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  2245. if (iface) renderModalIPs(iface);
  2246. }
  2247. } catch (err) {
  2248. showToast('Error', err.message, 'error');
  2249. }
  2250. }
  2251. async function saveInterfaceMetadata() {
  2252. const role = document.getElementById('modal-iface-role').value;
  2253. const desc = document.getElementById('modal-iface-desc').value.trim();
  2254. try {
  2255. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/metadata`, {
  2256. method: 'POST',
  2257. headers: { 'Content-Type': 'application/json' },
  2258. body: JSON.stringify({ role, description: desc })
  2259. });
  2260. if (res.ok) {
  2261. showToast('Saved', 'Metadata updated', 'success');
  2262. closeIfaceModal();
  2263. fetchData(false);
  2264. }
  2265. } catch (err) {
  2266. showToast('Error', err.message, 'error');
  2267. }
  2268. }
  2269. // ======================== MIKROTIK FIREWALL (/ip firewall) ========================
  2270. state.fwSubTab = 'filter';
  2271. state.routesSubTab = 'routes';
  2272. function renderRuleFlag(disabled, hasComment) {
  2273. let flags = '';
  2274. if (disabled) flags += '<span class="text-rose-400 font-bold" title="Disabled">X</span>';
  2275. if (hasComment) flags += '<span class="text-amber-400 font-bold ml-1" title="Has Comment">C</span>';
  2276. return flags || '<span class="text-slate-600">-</span>';
  2277. }
  2278. function renderActionBadge(action) {
  2279. const act = (action || '').toLowerCase();
  2280. let color = 'bg-slate-800 text-slate-300';
  2281. if (act === 'accept') color = 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30';
  2282. else if (act === 'drop' || act === 'reject') color = 'bg-rose-500/20 text-rose-300 border border-rose-500/30';
  2283. else if (act === 'masquerade' || act === 'src-nat' || act === 'dst-nat') color = 'bg-amber-500/20 text-amber-300 border border-amber-500/30';
  2284. else if (act.startsWith('mark-')) color = 'bg-purple-500/20 text-purple-300 border border-purple-500/30';
  2285. else if (act === 'log') color = 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30';
  2286. return `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold ${color}">${action}</span>`;
  2287. }
  2288. function switchFWSubTab(tab) {
  2289. state.fwSubTab = tab;
  2290. const tabs = ['filter', 'nat', 'mangle', 'addrlist', 'geo', 'connections'];
  2291. tabs.forEach(t => {
  2292. const panel = document.getElementById(`fw-subtab-${t}`);
  2293. const btn = document.getElementById(`fw-subtab-btn-${t}`);
  2294. if (panel) {
  2295. if (t === tab) panel.classList.remove('hidden');
  2296. else panel.classList.add('hidden');
  2297. }
  2298. if (btn) {
  2299. if (t === tab) {
  2300. 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';
  2301. } else {
  2302. 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';
  2303. }
  2304. }
  2305. });
  2306. const addBtn = document.getElementById('fw-primary-add-btn');
  2307. if (addBtn) {
  2308. if (tab === 'filter') addBtn.innerHTML = '<span>+ Add Filter Rule</span>';
  2309. else if (tab === 'nat') addBtn.innerHTML = '<span>+ Add NAT Rule</span>';
  2310. else if (tab === 'mangle') addBtn.innerHTML = '<span>+ Add Mangle Rule</span>';
  2311. else if (tab === 'addrlist') addBtn.innerHTML = '<span>+ Add Address List</span>';
  2312. else if (tab === 'geo') addBtn.innerHTML = '<span>⚙️ Schedule Settings</span>';
  2313. else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
  2314. }
  2315. if (tab === 'geo') loadGeoIP();
  2316. if (tab === 'connections') loadConnections();
  2317. }
  2318. function openCurrentFWModal() {
  2319. if (state.fwSubTab === 'filter') openAddFilterModal();
  2320. else if (state.fwSubTab === 'nat') openAddNATModal();
  2321. else if (state.fwSubTab === 'mangle') openAddMangleModal();
  2322. else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
  2323. else if (state.fwSubTab === 'geo') openGeoIntervalModal();
  2324. else if (state.fwSubTab === 'connections') loadConnections();
  2325. }
  2326. async function loadFirewall(populateDropdowns = true) {
  2327. try {
  2328. const [summaryRes, filterRes, natRes, mangleRes, addrlistRes, geoStatusRes, geoCountriesRes] = await Promise.all([
  2329. fetch(`${API_BASE}/firewall/summary`),
  2330. fetch(`${API_BASE}/firewall/filter`),
  2331. fetch(`${API_BASE}/firewall/nat`),
  2332. fetch(`${API_BASE}/firewall/mangle`),
  2333. fetch(`${API_BASE}/firewall/address-lists`),
  2334. fetch(`${API_BASE}/firewall/geoip/status`),
  2335. fetch(`${API_BASE}/firewall/geoip/countries`)
  2336. ]);
  2337. if (summaryRes.ok) state.fwSummary = await summaryRes.json();
  2338. if (filterRes.ok) state.filterRules = await filterRes.json();
  2339. if (natRes.ok) state.natRules = await natRes.json();
  2340. if (mangleRes.ok) state.mangleRules = await mangleRes.json();
  2341. if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
  2342. if (geoStatusRes.ok) state.geoStatus = await geoStatusRes.json();
  2343. if (geoCountriesRes.ok) state.geoCountries = await geoCountriesRes.json();
  2344. // Badges
  2345. const bFilter = document.getElementById('fw-badge-filter');
  2346. if (bFilter) bFilter.innerText = (state.filterRules || []).length;
  2347. const bNat = document.getElementById('fw-badge-nat');
  2348. if (bNat) bNat.innerText = (state.natRules || []).length;
  2349. const bMangle = document.getElementById('fw-badge-mangle');
  2350. if (bMangle) bMangle.innerText = (state.mangleRules || []).length;
  2351. const bAddr = document.getElementById('fw-badge-addrlist');
  2352. if (bAddr) bAddr.innerText = (state.addressLists || []).length;
  2353. const bGeo = document.getElementById('fw-badge-geo');
  2354. if (bGeo) bGeo.innerText = state.geoStatus?.enabled_count || 0;
  2355. renderFilterRules();
  2356. renderNATRules();
  2357. renderMangleRules();
  2358. renderAddressLists();
  2359. renderGeoCountries();
  2360. if (state.fwSubTab === 'connections') {
  2361. loadConnections();
  2362. }
  2363. } catch (err) {
  2364. console.error('Failed to load firewall:', err);
  2365. }
  2366. }
  2367. // ----------------- Filter Rules -----------------
  2368. function renderFilterRules() {
  2369. const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
  2370. const tbody = document.getElementById('filter-table-body');
  2371. const empty = document.getElementById('filter-empty');
  2372. if (!tbody) return;
  2373. tbody.innerHTML = '';
  2374. const rules = (state.filterRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2375. document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
  2376. if (rules.length === 0) {
  2377. empty?.classList.remove('hidden');
  2378. return;
  2379. }
  2380. empty?.classList.add('hidden');
  2381. rules.forEach((r, idx) => {
  2382. const tr = document.createElement('tr');
  2383. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2384. const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
  2385. const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
  2386. tr.innerHTML = `
  2387. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  2388. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  2389. <td class="py-2.5 px-3 font-bold text-white">${r.chain}</td>
  2390. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  2391. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  2392. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}</td>
  2393. <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
  2394. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  2395. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  2396. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2397. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2398. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2399. </td>
  2400. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2401. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2402. <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2403. <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2404. <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>
  2405. <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2406. <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2407. </td>
  2408. `;
  2409. tbody.appendChild(tr);
  2410. });
  2411. }
  2412. function formatTarget(addr, list, geo) {
  2413. const parts = [];
  2414. if (addr) parts.push(`<span>${addr}</span>`);
  2415. if (list) {
  2416. const inv = list.startsWith('!') ? '!' : '';
  2417. const clean = list.replace(/^!/, '');
  2418. 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>`);
  2419. }
  2420. if (geo) {
  2421. const inv = geo.startsWith('!') ? '!' : '';
  2422. const clean = geo.replace(/^!/, '').replace(/^geo:/, '');
  2423. 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>`);
  2424. }
  2425. if (parts.length === 0) return '<span class="text-slate-600">0.0.0.0/0</span>';
  2426. return parts.join(' ');
  2427. }
  2428. function populateInterfaceSelect(selectId, currentVal = '') {
  2429. const sel = document.getElementById(selectId);
  2430. if (!sel) return;
  2431. sel.innerHTML = '<option value="">(Any Interface)</option>';
  2432. (state.interfaces || []).forEach(i => {
  2433. const opt = document.createElement('option');
  2434. opt.value = i.name;
  2435. opt.innerText = `${i.name} (${i.role || i.type})`;
  2436. if (i.name === currentVal) opt.selected = true;
  2437. sel.appendChild(opt);
  2438. });
  2439. }
  2440. function populateAddressListSelect(selectId, currentVal = '') {
  2441. const sel = document.getElementById(selectId);
  2442. if (!sel) return;
  2443. sel.innerHTML = '<option value="">(None)</option>';
  2444. const cleanVal = (currentVal || '').replace(/^!/, '');
  2445. const customNames = Array.from(new Set((state.addressLists || []).map(a => a.name))).sort();
  2446. customNames.forEach(name => {
  2447. const count = (state.addressLists || []).filter(a => a.name === name).length;
  2448. const opt = document.createElement('option');
  2449. opt.value = name;
  2450. opt.innerText = `${name} (${count} entries)`;
  2451. if (name === cleanVal) opt.selected = true;
  2452. sel.appendChild(opt);
  2453. });
  2454. if (cleanVal && !sel.querySelector(`option[value="${cleanVal}"]`)) {
  2455. const opt = document.createElement('option');
  2456. opt.value = cleanVal;
  2457. opt.innerText = cleanVal;
  2458. opt.selected = true;
  2459. sel.appendChild(opt);
  2460. }
  2461. }
  2462. function populateGeoIPSelect(selectId, currentVal = '') {
  2463. const sel = document.getElementById(selectId);
  2464. if (!sel) return;
  2465. sel.innerHTML = '<option value="">(None)</option>';
  2466. const cleanVal = (currentVal || '').replace(/^!/, '').replace(/^geo:/, '').toUpperCase();
  2467. // Presets optgroup
  2468. const grpPresets = document.createElement('optgroup');
  2469. grpPresets.label = '⚡ Regional Presets';
  2470. const presets = [
  2471. { code: 'EU', label: '🇪🇺 European Union (EU - 27 countries)' },
  2472. { code: 'BALKANS', label: '🏛️ Balkans (GR, CY, BG, RO, AL, etc.)' },
  2473. { code: 'BLOCKLIST', label: '🛡️ High-Risk Blocklist (CN, RU, IR, KP, BY)' }
  2474. ];
  2475. presets.forEach(p => {
  2476. const opt = document.createElement('option');
  2477. opt.value = p.code;
  2478. opt.innerText = p.label;
  2479. if (p.code === cleanVal) opt.selected = true;
  2480. grpPresets.appendChild(opt);
  2481. });
  2482. sel.appendChild(grpPresets);
  2483. // All Countries optgroup
  2484. const grpCountries = document.createElement('optgroup');
  2485. grpCountries.label = '🌍 All Countries';
  2486. const countries = (state.geoCountries || []).slice().sort((a, b) => a.name.localeCompare(b.name));
  2487. countries.forEach(c => {
  2488. const opt = document.createElement('option');
  2489. opt.value = c.code;
  2490. const subnetsInfo = c.subnet_count ? ` [${c.subnet_count.toLocaleString()} subnets]` : '';
  2491. opt.innerText = `${c.name} (${c.code})${subnetsInfo}`;
  2492. if (c.code === cleanVal) opt.selected = true;
  2493. grpCountries.appendChild(opt);
  2494. });
  2495. sel.appendChild(grpCountries);
  2496. }
  2497. function openAddFilterModal() {
  2498. document.getElementById('filter-modal-title').innerText = 'Add Firewall Filter Rule';
  2499. document.getElementById('filter-modal-id').value = '';
  2500. document.getElementById('filter-modal-chain').value = 'forward';
  2501. document.getElementById('filter-modal-action').value = 'accept';
  2502. document.getElementById('filter-modal-proto').value = 'all';
  2503. document.getElementById('filter-modal-src').value = '';
  2504. document.getElementById('filter-modal-dst').value = '';
  2505. document.getElementById('filter-modal-sport').value = '';
  2506. document.getElementById('filter-modal-dport').value = '';
  2507. document.getElementById('filter-modal-connmark').value = '';
  2508. document.getElementById('filter-modal-comment').value = '';
  2509. document.getElementById('filter-modal-disabled').checked = false;
  2510. document.getElementById('filter-modal-cs-established').checked = false;
  2511. document.getElementById('filter-modal-cs-related').checked = false;
  2512. document.getElementById('filter-modal-cs-new').checked = false;
  2513. document.getElementById('filter-modal-cs-invalid').checked = false;
  2514. populateInterfaceSelect('filter-modal-iniface');
  2515. populateInterfaceSelect('filter-modal-outiface');
  2516. if (document.getElementById('filter-modal-srclist-inv')) document.getElementById('filter-modal-srclist-inv').checked = false;
  2517. if (document.getElementById('filter-modal-dstlist-inv')) document.getElementById('filter-modal-dstlist-inv').checked = false;
  2518. populateAddressListSelect('filter-modal-srclist');
  2519. populateAddressListSelect('filter-modal-dstlist');
  2520. if (document.getElementById('filter-modal-srcgeoip-inv')) document.getElementById('filter-modal-srcgeoip-inv').checked = false;
  2521. if (document.getElementById('filter-modal-dstgeoip-inv')) document.getElementById('filter-modal-dstgeoip-inv').checked = false;
  2522. populateGeoIPSelect('filter-modal-srcgeoip');
  2523. populateGeoIPSelect('filter-modal-dstgeoip');
  2524. toggleFilterActionFields();
  2525. document.getElementById('filter-modal').classList.remove('hidden');
  2526. }
  2527. function openEditFilterModal(id) {
  2528. const r = (state.filterRules || []).find(rule => rule.id === id);
  2529. if (!r) return;
  2530. document.getElementById('filter-modal-title').innerText = `Edit Filter Rule (#${r.order})`;
  2531. document.getElementById('filter-modal-id').value = r.id;
  2532. document.getElementById('filter-modal-chain').value = r.chain || 'forward';
  2533. document.getElementById('filter-modal-action').value = r.action || 'accept';
  2534. document.getElementById('filter-modal-proto').value = r.protocol || 'all';
  2535. document.getElementById('filter-modal-src').value = r.src_address || '';
  2536. document.getElementById('filter-modal-dst').value = r.dst_address || '';
  2537. document.getElementById('filter-modal-sport').value = r.src_port || '';
  2538. document.getElementById('filter-modal-dport').value = r.dst_port || '';
  2539. document.getElementById('filter-modal-connmark').value = r.connection_mark || '';
  2540. document.getElementById('filter-modal-comment').value = r.comment || '';
  2541. document.getElementById('filter-modal-disabled').checked = !!r.disabled;
  2542. const states = r.connection_state || [];
  2543. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  2544. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  2545. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  2546. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  2547. populateInterfaceSelect('filter-modal-iniface', r.in_interface);
  2548. populateInterfaceSelect('filter-modal-outiface', r.out_interface);
  2549. const srcInv = (r.src_address_list || '').startsWith('!');
  2550. const dstInv = (r.dst_address_list || '').startsWith('!');
  2551. if (document.getElementById('filter-modal-srclist-inv')) document.getElementById('filter-modal-srclist-inv').checked = srcInv;
  2552. if (document.getElementById('filter-modal-dstlist-inv')) document.getElementById('filter-modal-dstlist-inv').checked = dstInv;
  2553. populateAddressListSelect('filter-modal-srclist', r.src_address_list || '');
  2554. populateAddressListSelect('filter-modal-dstlist', r.dst_address_list || '');
  2555. const srcGeoInv = (r.src_geoip || '').startsWith('!');
  2556. const dstGeoInv = (r.dst_geoip || '').startsWith('!');
  2557. if (document.getElementById('filter-modal-srcgeoip-inv')) document.getElementById('filter-modal-srcgeoip-inv').checked = srcGeoInv;
  2558. if (document.getElementById('filter-modal-dstgeoip-inv')) document.getElementById('filter-modal-dstgeoip-inv').checked = dstGeoInv;
  2559. populateGeoIPSelect('filter-modal-srcgeoip', r.src_geoip || '');
  2560. populateGeoIPSelect('filter-modal-dstgeoip', r.dst_geoip || '');
  2561. toggleFilterActionFields();
  2562. document.getElementById('filter-modal').classList.remove('hidden');
  2563. }
  2564. function closeFilterModal() {
  2565. document.getElementById('filter-modal').classList.add('hidden');
  2566. }
  2567. function toggleFilterActionFields() {
  2568. const act = document.getElementById('filter-modal-action').value;
  2569. const rejectBox = document.getElementById('filter-action-reject-box');
  2570. if (rejectBox) {
  2571. if (act === 'reject') rejectBox.classList.remove('hidden');
  2572. else rejectBox.classList.add('hidden');
  2573. }
  2574. }
  2575. async function submitSaveFilterRule(e) {
  2576. e.preventDefault();
  2577. const id = document.getElementById('filter-modal-id').value;
  2578. const chain = document.getElementById('filter-modal-chain').value;
  2579. const action = document.getElementById('filter-modal-action').value;
  2580. const proto = document.getElementById('filter-modal-proto').value;
  2581. const src = document.getElementById('filter-modal-src').value.trim();
  2582. const dst = document.getElementById('filter-modal-dst').value.trim();
  2583. const sport = document.getElementById('filter-modal-sport').value.trim();
  2584. const dport = document.getElementById('filter-modal-dport').value.trim();
  2585. const inIface = document.getElementById('filter-modal-iniface').value;
  2586. const outIface = document.getElementById('filter-modal-outiface').value;
  2587. const connmark = document.getElementById('filter-modal-connmark').value.trim();
  2588. let srclist = document.getElementById('filter-modal-srclist')?.value || '';
  2589. if (srclist && document.getElementById('filter-modal-srclist-inv')?.checked) {
  2590. srclist = '!' + srclist.replace(/^!/, '');
  2591. }
  2592. let dstlist = document.getElementById('filter-modal-dstlist')?.value || '';
  2593. if (dstlist && document.getElementById('filter-modal-dstlist-inv')?.checked) {
  2594. dstlist = '!' + dstlist.replace(/^!/, '');
  2595. }
  2596. let srcgeoip = document.getElementById('filter-modal-srcgeoip')?.value || '';
  2597. if (srcgeoip && document.getElementById('filter-modal-srcgeoip-inv')?.checked) {
  2598. srcgeoip = '!' + srcgeoip.replace(/^!/, '');
  2599. }
  2600. let dstgeoip = document.getElementById('filter-modal-dstgeoip')?.value || '';
  2601. if (dstgeoip && document.getElementById('filter-modal-dstgeoip-inv')?.checked) {
  2602. dstgeoip = '!' + dstgeoip.replace(/^!/, '');
  2603. }
  2604. const comment = document.getElementById('filter-modal-comment').value.trim();
  2605. const disabled = document.getElementById('filter-modal-disabled').checked;
  2606. const rejectWith = document.getElementById('filter-modal-rejectwith')?.value || '';
  2607. const states = [];
  2608. if (document.getElementById('filter-modal-cs-established').checked) states.push('established');
  2609. if (document.getElementById('filter-modal-cs-related').checked) states.push('related');
  2610. if (document.getElementById('filter-modal-cs-new').checked) states.push('new');
  2611. if (document.getElementById('filter-modal-cs-invalid').checked) states.push('invalid');
  2612. try {
  2613. const res = await fetch(`${API_BASE}/firewall/filter`, {
  2614. method: 'POST',
  2615. headers: { 'Content-Type': 'application/json' },
  2616. body: JSON.stringify({
  2617. id,
  2618. chain,
  2619. action,
  2620. reject_with: rejectWith,
  2621. protocol: proto,
  2622. src_address: src,
  2623. dst_address: dst,
  2624. src_port: sport,
  2625. dst_port: dport,
  2626. in_interface: inIface,
  2627. out_interface: outIface,
  2628. connection_state: states,
  2629. connection_mark: connmark,
  2630. src_address_list: srclist,
  2631. dst_address_list: dstlist,
  2632. src_geoip: srcgeoip,
  2633. dst_geoip: dstgeoip,
  2634. comment,
  2635. disabled
  2636. })
  2637. });
  2638. if (res.ok) {
  2639. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  2640. closeFilterModal();
  2641. loadFirewall(false);
  2642. } else {
  2643. const err = await res.json();
  2644. showToast('Error', err.message, 'error');
  2645. }
  2646. } catch (err) {
  2647. showToast('Error', err.message, 'error');
  2648. }
  2649. }
  2650. async function moveFilterRule(id, dir) {
  2651. try {
  2652. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  2653. method: 'POST',
  2654. headers: { 'Content-Type': 'application/json' },
  2655. body: JSON.stringify({ direction: dir })
  2656. });
  2657. if (res.ok) loadFirewall(false);
  2658. } catch (err) {
  2659. showToast('Error', err.message, 'error');
  2660. }
  2661. }
  2662. async function toggleFilterRuleState(id, disabled) {
  2663. try {
  2664. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  2665. method: 'POST',
  2666. headers: { 'Content-Type': 'application/json' },
  2667. body: JSON.stringify({ disabled })
  2668. });
  2669. if (res.ok) loadFirewall(false);
  2670. } catch (err) {
  2671. showToast('Error', err.message, 'error');
  2672. }
  2673. }
  2674. async function deleteFilterRule(id) {
  2675. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  2676. try {
  2677. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  2678. if (res.ok) {
  2679. showToast('Deleted', 'Filter rule removed', 'success');
  2680. loadFirewall(false);
  2681. }
  2682. } catch (err) {
  2683. showToast('Error', err.message, 'error');
  2684. }
  2685. }
  2686. // ----------------- NAT Rules -----------------
  2687. function renderNATRules() {
  2688. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  2689. const tbody = document.getElementById('nat-table-body');
  2690. const empty = document.getElementById('nat-empty');
  2691. if (!tbody) return;
  2692. tbody.innerHTML = '';
  2693. const rules = (state.natRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2694. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  2695. if (rules.length === 0) {
  2696. empty?.classList.remove('hidden');
  2697. return;
  2698. }
  2699. empty?.classList.add('hidden');
  2700. rules.forEach((r, idx) => {
  2701. const tr = document.createElement('tr');
  2702. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2703. const toTarget = [r.to_addresses, r.to_ports].filter(Boolean).join(':');
  2704. const ifaces = [r.out_interface ? 'out:' + r.out_interface : '', r.in_interface ? 'in:' + r.in_interface : ''].filter(Boolean).join(' ');
  2705. tr.innerHTML = `
  2706. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  2707. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  2708. <td class="py-2.5 px-3 font-bold text-amber-400">${r.chain}</td>
  2709. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  2710. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  2711. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}${r.dst_port ? ':' + r.dst_port : ''}</td>
  2712. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  2713. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  2714. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${toTarget || '-'}</td>
  2715. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2716. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2717. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2718. </td>
  2719. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2720. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2721. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2722. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2723. <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>
  2724. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2725. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2726. </td>
  2727. `;
  2728. tbody.appendChild(tr);
  2729. });
  2730. }
  2731. function openAddNATModal() {
  2732. document.getElementById('nat-modal-title').innerText = 'Add NAT Rule';
  2733. document.getElementById('nat-modal-id').value = '';
  2734. document.getElementById('nat-modal-chain').value = 'srcnat';
  2735. document.getElementById('nat-modal-action').value = 'masquerade';
  2736. document.getElementById('nat-modal-toaddr').value = '';
  2737. document.getElementById('nat-modal-toport').value = '';
  2738. document.getElementById('nat-modal-proto').value = 'all';
  2739. document.getElementById('nat-modal-src').value = '';
  2740. document.getElementById('nat-modal-dst').value = '';
  2741. document.getElementById('nat-modal-dport').value = '';
  2742. document.getElementById('nat-modal-comment').value = '';
  2743. document.getElementById('nat-modal-disabled').checked = false;
  2744. populateInterfaceSelect('nat-modal-iniface');
  2745. populateInterfaceSelect('nat-modal-outiface');
  2746. populateAddressListSelect('nat-modal-srclist');
  2747. populateAddressListSelect('nat-modal-dstlist');
  2748. const srcInvEl = document.getElementById('nat-modal-srclist-inv');
  2749. if (srcInvEl) srcInvEl.checked = false;
  2750. const dstInvEl = document.getElementById('nat-modal-dstlist-inv');
  2751. if (dstInvEl) dstInvEl.checked = false;
  2752. populateGeoIPSelect('nat-modal-srcgeoip');
  2753. populateGeoIPSelect('nat-modal-dstgeoip');
  2754. const srcGeoInvEl = document.getElementById('nat-modal-srcgeoip-inv');
  2755. if (srcGeoInvEl) srcGeoInvEl.checked = false;
  2756. const dstGeoInvEl = document.getElementById('nat-modal-dstgeoip-inv');
  2757. if (dstGeoInvEl) dstGeoInvEl.checked = false;
  2758. toggleNATActionFields();
  2759. document.getElementById('nat-modal').classList.remove('hidden');
  2760. }
  2761. function openEditNATModal(id) {
  2762. const r = (state.natRules || []).find(rule => rule.id === id);
  2763. if (!r) return;
  2764. document.getElementById('nat-modal-title').innerText = `Edit NAT Rule (#${r.order})`;
  2765. document.getElementById('nat-modal-id').value = r.id;
  2766. document.getElementById('nat-modal-chain').value = r.chain || 'srcnat';
  2767. document.getElementById('nat-modal-action').value = r.action || 'masquerade';
  2768. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  2769. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  2770. document.getElementById('nat-modal-proto').value = r.protocol || 'all';
  2771. document.getElementById('nat-modal-src').value = r.src_address || '';
  2772. document.getElementById('nat-modal-dst').value = r.dst_address || '';
  2773. document.getElementById('nat-modal-dport').value = r.dst_port || '';
  2774. document.getElementById('nat-modal-comment').value = r.comment || '';
  2775. document.getElementById('nat-modal-disabled').checked = !!r.disabled;
  2776. populateInterfaceSelect('nat-modal-iniface', r.in_interface);
  2777. populateInterfaceSelect('nat-modal-outiface', r.out_interface);
  2778. const srcInv = (r.src_address_list || '').startsWith('!');
  2779. const dstInv = (r.dst_address_list || '').startsWith('!');
  2780. const srcInvEl = document.getElementById('nat-modal-srclist-inv');
  2781. if (srcInvEl) srcInvEl.checked = srcInv;
  2782. const dstInvEl = document.getElementById('nat-modal-dstlist-inv');
  2783. if (dstInvEl) dstInvEl.checked = dstInv;
  2784. populateAddressListSelect('nat-modal-srclist', r.src_address_list || '');
  2785. populateAddressListSelect('nat-modal-dstlist', r.dst_address_list || '');
  2786. const srcGeoInv = (r.src_geoip || '').startsWith('!');
  2787. const dstGeoInv = (r.dst_geoip || '').startsWith('!');
  2788. const srcGeoInvEl = document.getElementById('nat-modal-srcgeoip-inv');
  2789. if (srcGeoInvEl) srcGeoInvEl.checked = srcGeoInv;
  2790. const dstGeoInvEl = document.getElementById('nat-modal-dstgeoip-inv');
  2791. if (dstGeoInvEl) dstGeoInvEl.checked = dstGeoInv;
  2792. populateGeoIPSelect('nat-modal-srcgeoip', r.src_geoip || '');
  2793. populateGeoIPSelect('nat-modal-dstgeoip', r.dst_geoip || '');
  2794. toggleNATActionFields();
  2795. document.getElementById('nat-modal').classList.remove('hidden');
  2796. }
  2797. function closeNATModal() {
  2798. document.getElementById('nat-modal').classList.add('hidden');
  2799. }
  2800. function toggleNATChainFields() {
  2801. const ch = document.getElementById('nat-modal-chain').value;
  2802. const actSel = document.getElementById('nat-modal-action');
  2803. if (ch === 'srcnat' && actSel.value === 'dst-nat') {
  2804. actSel.value = 'masquerade';
  2805. } else if (ch === 'dstnat' && actSel.value === 'masquerade') {
  2806. actSel.value = 'dst-nat';
  2807. }
  2808. toggleNATActionFields();
  2809. }
  2810. function toggleNATActionFields() {
  2811. const act = document.getElementById('nat-modal-action').value;
  2812. const toBox = document.getElementById('nat-action-to-box');
  2813. if (toBox) {
  2814. if (act === 'masquerade' || act === 'accept') toBox.classList.add('hidden');
  2815. else toBox.classList.remove('hidden');
  2816. }
  2817. }
  2818. async function submitSaveNATRule(e) {
  2819. e.preventDefault();
  2820. const id = document.getElementById('nat-modal-id').value;
  2821. const chain = document.getElementById('nat-modal-chain').value;
  2822. const action = document.getElementById('nat-modal-action').value;
  2823. const toaddr = document.getElementById('nat-modal-toaddr').value.trim();
  2824. const toport = document.getElementById('nat-modal-toport').value.trim();
  2825. const proto = document.getElementById('nat-modal-proto').value;
  2826. const src = document.getElementById('nat-modal-src').value.trim();
  2827. const dst = document.getElementById('nat-modal-dst').value.trim();
  2828. const dport = document.getElementById('nat-modal-dport').value.trim();
  2829. const inIface = document.getElementById('nat-modal-iniface').value;
  2830. const outIface = document.getElementById('nat-modal-outiface').value;
  2831. let srclist = document.getElementById('nat-modal-srclist')?.value || '';
  2832. if (srclist && document.getElementById('nat-modal-srclist-inv')?.checked) {
  2833. srclist = '!' + srclist.replace(/^!/, '');
  2834. }
  2835. let dstlist = document.getElementById('nat-modal-dstlist')?.value || '';
  2836. if (dstlist && document.getElementById('nat-modal-dstlist-inv')?.checked) {
  2837. dstlist = '!' + dstlist.replace(/^!/, '');
  2838. }
  2839. let srcgeoip = document.getElementById('nat-modal-srcgeoip')?.value || '';
  2840. if (srcgeoip && document.getElementById('nat-modal-srcgeoip-inv')?.checked) {
  2841. srcgeoip = '!' + srcgeoip.replace(/^!/, '');
  2842. }
  2843. let dstgeoip = document.getElementById('nat-modal-dstgeoip')?.value || '';
  2844. if (dstgeoip && document.getElementById('nat-modal-dstgeoip-inv')?.checked) {
  2845. dstgeoip = '!' + dstgeoip.replace(/^!/, '');
  2846. }
  2847. const comment = document.getElementById('nat-modal-comment').value.trim();
  2848. const disabled = document.getElementById('nat-modal-disabled').checked;
  2849. try {
  2850. const res = await fetch(`${API_BASE}/firewall/nat`, {
  2851. method: 'POST',
  2852. headers: { 'Content-Type': 'application/json' },
  2853. body: JSON.stringify({
  2854. id,
  2855. chain,
  2856. action,
  2857. to_addresses: toaddr,
  2858. to_ports: toport,
  2859. protocol: proto,
  2860. src_address: src,
  2861. dst_address: dst,
  2862. dst_port: dport,
  2863. in_interface: inIface,
  2864. out_interface: outIface,
  2865. src_address_list: srclist,
  2866. dst_address_list: dstlist,
  2867. src_geoip: srcgeoip,
  2868. dst_geoip: dstgeoip,
  2869. comment,
  2870. disabled
  2871. })
  2872. });
  2873. if (res.ok) {
  2874. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  2875. closeNATModal();
  2876. loadFirewall(false);
  2877. }
  2878. } catch (err) {
  2879. showToast('Error', err.message, 'error');
  2880. }
  2881. }
  2882. async function moveNATRule(id, dir) {
  2883. try {
  2884. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  2885. method: 'POST',
  2886. headers: { 'Content-Type': 'application/json' },
  2887. body: JSON.stringify({ direction: dir })
  2888. });
  2889. if (res.ok) loadFirewall(false);
  2890. } catch (err) {
  2891. showToast('Error', err.message, 'error');
  2892. }
  2893. }
  2894. async function toggleNATRuleState(id, disabled) {
  2895. try {
  2896. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  2897. method: 'POST',
  2898. headers: { 'Content-Type': 'application/json' },
  2899. body: JSON.stringify({ disabled })
  2900. });
  2901. if (res.ok) loadFirewall(false);
  2902. } catch (err) {
  2903. showToast('Error', err.message, 'error');
  2904. }
  2905. }
  2906. async function deleteNATRule(id) {
  2907. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  2908. try {
  2909. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  2910. if (res.ok) {
  2911. showToast('Deleted', 'NAT rule removed', 'success');
  2912. loadFirewall(false);
  2913. }
  2914. } catch (err) {
  2915. showToast('Error', err.message, 'error');
  2916. }
  2917. }
  2918. // ----------------- Mangle Rules -----------------
  2919. function renderMangleRules() {
  2920. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  2921. const tbody = document.getElementById('mangle-table-body');
  2922. const empty = document.getElementById('mangle-empty');
  2923. if (!tbody) return;
  2924. tbody.innerHTML = '';
  2925. const rules = (state.mangleRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2926. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  2927. if (rules.length === 0) {
  2928. empty?.classList.remove('hidden');
  2929. return;
  2930. }
  2931. empty?.classList.add('hidden');
  2932. rules.forEach((r, idx) => {
  2933. const tr = document.createElement('tr');
  2934. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2935. const markVal = r.new_connection_mark || r.new_routing_mark || r.new_packet_mark || r.new_mss || (r.new_dscp ? 'DSCP:' + r.new_dscp : '');
  2936. tr.innerHTML = `
  2937. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  2938. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  2939. <td class="py-2.5 px-3 font-bold text-purple-400">${r.chain}</td>
  2940. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  2941. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  2942. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  2943. <td class="py-2.5 px-3 font-mono font-bold text-cyan-300">${markVal || '-'}</td>
  2944. <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>
  2945. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2946. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2947. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2948. </td>
  2949. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2950. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2951. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2952. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2953. <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>
  2954. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2955. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2956. </td>
  2957. `;
  2958. tbody.appendChild(tr);
  2959. });
  2960. }
  2961. function openAddMangleModal() {
  2962. document.getElementById('mangle-modal-title').innerText = 'Add Mangle Rule';
  2963. document.getElementById('mangle-modal-id').value = '';
  2964. document.getElementById('mangle-modal-chain').value = 'prerouting';
  2965. document.getElementById('mangle-modal-action').value = 'mark-connection';
  2966. document.getElementById('mangle-modal-newmark').value = '';
  2967. document.getElementById('mangle-modal-passthrough').checked = true;
  2968. document.getElementById('mangle-modal-src').value = '';
  2969. document.getElementById('mangle-modal-dst').value = '';
  2970. document.getElementById('mangle-modal-connmark').value = '';
  2971. document.getElementById('mangle-modal-comment').value = '';
  2972. document.getElementById('mangle-modal-disabled').checked = false;
  2973. populateInterfaceSelect('mangle-modal-iniface');
  2974. populateAddressListSelect('mangle-modal-srclist');
  2975. populateAddressListSelect('mangle-modal-dstlist');
  2976. const srcInvEl = document.getElementById('mangle-modal-srclist-inv');
  2977. if (srcInvEl) srcInvEl.checked = false;
  2978. const dstInvEl = document.getElementById('mangle-modal-dstlist-inv');
  2979. if (dstInvEl) dstInvEl.checked = false;
  2980. populateGeoIPSelect('mangle-modal-srcgeoip');
  2981. populateGeoIPSelect('mangle-modal-dstgeoip');
  2982. const srcGeoInvEl = document.getElementById('mangle-modal-srcgeoip-inv');
  2983. if (srcGeoInvEl) srcGeoInvEl.checked = false;
  2984. const dstGeoInvEl = document.getElementById('mangle-modal-dstgeoip-inv');
  2985. if (dstGeoInvEl) dstGeoInvEl.checked = false;
  2986. document.getElementById('mangle-modal').classList.remove('hidden');
  2987. }
  2988. function openEditMangleModal(id) {
  2989. const r = (state.mangleRules || []).find(rule => rule.id === id);
  2990. if (!r) return;
  2991. document.getElementById('mangle-modal-title').innerText = `Edit Mangle Rule (#${r.order})`;
  2992. document.getElementById('mangle-modal-id').value = r.id;
  2993. document.getElementById('mangle-modal-chain').value = r.chain || 'prerouting';
  2994. document.getElementById('mangle-modal-action').value = r.action || 'mark-connection';
  2995. document.getElementById('mangle-modal-newmark').value = r.new_connection_mark || r.new_routing_mark || r.new_packet_mark || r.new_mss || '';
  2996. document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  2997. document.getElementById('mangle-modal-src').value = r.src_address || '';
  2998. document.getElementById('mangle-modal-dst').value = r.dst_address || '';
  2999. document.getElementById('mangle-modal-connmark').value = r.connection_mark || '';
  3000. document.getElementById('mangle-modal-comment').value = r.comment || '';
  3001. document.getElementById('mangle-modal-disabled').checked = !!r.disabled;
  3002. populateInterfaceSelect('mangle-modal-iniface', r.in_interface);
  3003. const srcInv = (r.src_address_list || '').startsWith('!');
  3004. const dstInv = (r.dst_address_list || '').startsWith('!');
  3005. const srcInvEl = document.getElementById('mangle-modal-srclist-inv');
  3006. if (srcInvEl) srcInvEl.checked = srcInv;
  3007. const dstInvEl = document.getElementById('mangle-modal-dstlist-inv');
  3008. if (dstInvEl) dstInvEl.checked = dstInv;
  3009. populateAddressListSelect('mangle-modal-srclist', r.src_address_list || '');
  3010. populateAddressListSelect('mangle-modal-dstlist', r.dst_address_list || '');
  3011. const srcGeoInv = (r.src_geoip || '').startsWith('!');
  3012. const dstGeoInv = (r.dst_geoip || '').startsWith('!');
  3013. const srcGeoInvEl = document.getElementById('mangle-modal-srcgeoip-inv');
  3014. if (srcGeoInvEl) srcGeoInvEl.checked = srcGeoInv;
  3015. const dstGeoInvEl = document.getElementById('mangle-modal-dstgeoip-inv');
  3016. if (dstGeoInvEl) dstGeoInvEl.checked = dstGeoInv;
  3017. populateGeoIPSelect('mangle-modal-srcgeoip', r.src_geoip || '');
  3018. populateGeoIPSelect('mangle-modal-dstgeoip', r.dst_geoip || '');
  3019. document.getElementById('mangle-modal').classList.remove('hidden');
  3020. }
  3021. function closeMangleModal() {
  3022. document.getElementById('mangle-modal').classList.add('hidden');
  3023. }
  3024. function toggleMangleActionFields() {
  3025. // Handled smoothly by single dynamic input
  3026. }
  3027. async function submitSaveMangleRule(e) {
  3028. e.preventDefault();
  3029. const id = document.getElementById('mangle-modal-id').value;
  3030. const chain = document.getElementById('mangle-modal-chain').value;
  3031. const action = document.getElementById('mangle-modal-action').value;
  3032. const newmark = document.getElementById('mangle-modal-newmark').value.trim();
  3033. const passthrough = document.getElementById('mangle-modal-passthrough').checked;
  3034. const src = document.getElementById('mangle-modal-src').value.trim();
  3035. const dst = document.getElementById('mangle-modal-dst').value.trim();
  3036. const inIface = document.getElementById('mangle-modal-iniface').value;
  3037. let srclist = document.getElementById('mangle-modal-srclist')?.value || '';
  3038. if (srclist && document.getElementById('mangle-modal-srclist-inv')?.checked) {
  3039. srclist = '!' + srclist.replace(/^!/, '');
  3040. }
  3041. let dstlist = document.getElementById('mangle-modal-dstlist')?.value || '';
  3042. if (dstlist && document.getElementById('mangle-modal-dstlist-inv')?.checked) {
  3043. dstlist = '!' + dstlist.replace(/^!/, '');
  3044. }
  3045. let srcgeoip = document.getElementById('mangle-modal-srcgeoip')?.value || '';
  3046. if (srcgeoip && document.getElementById('mangle-modal-srcgeoip-inv')?.checked) {
  3047. srcgeoip = '!' + srcgeoip.replace(/^!/, '');
  3048. }
  3049. let dstgeoip = document.getElementById('mangle-modal-dstgeoip')?.value || '';
  3050. if (dstgeoip && document.getElementById('mangle-modal-dstgeoip-inv')?.checked) {
  3051. dstgeoip = '!' + dstgeoip.replace(/^!/, '');
  3052. }
  3053. const connmark = document.getElementById('mangle-modal-connmark').value.trim();
  3054. const comment = document.getElementById('mangle-modal-comment').value.trim();
  3055. const disabled = document.getElementById('mangle-modal-disabled').checked;
  3056. const payload = {
  3057. id,
  3058. chain,
  3059. action,
  3060. passthrough,
  3061. src_address: src,
  3062. dst_address: dst,
  3063. in_interface: inIface,
  3064. src_address_list: srclist,
  3065. dst_address_list: dstlist,
  3066. src_geoip: srcgeoip,
  3067. dst_geoip: dstgeoip,
  3068. connection_mark: connmark,
  3069. comment,
  3070. disabled
  3071. };
  3072. if (action === 'mark-connection') payload.new_connection_mark = newmark;
  3073. else if (action === 'mark-routing') payload.new_routing_mark = newmark;
  3074. else if (action === 'mark-packet') payload.new_packet_mark = newmark;
  3075. else if (action === 'change-mss') payload.new_mss = newmark || 'clamp-to-pmtu';
  3076. try {
  3077. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  3078. method: 'POST',
  3079. headers: { 'Content-Type': 'application/json' },
  3080. body: JSON.stringify(payload)
  3081. });
  3082. if (res.ok) {
  3083. showToast('Mangle Rule Saved', 'Marking rule applied', 'success');
  3084. closeMangleModal();
  3085. loadFirewall(false);
  3086. }
  3087. } catch (err) {
  3088. showToast('Error', err.message, 'error');
  3089. }
  3090. }
  3091. async function moveMangleRule(id, dir) {
  3092. try {
  3093. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  3094. method: 'POST',
  3095. headers: { 'Content-Type': 'application/json' },
  3096. body: JSON.stringify({ direction: dir })
  3097. });
  3098. if (res.ok) loadFirewall(false);
  3099. } catch (err) {
  3100. showToast('Error', err.message, 'error');
  3101. }
  3102. }
  3103. async function toggleMangleRuleState(id, disabled) {
  3104. try {
  3105. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  3106. method: 'POST',
  3107. headers: { 'Content-Type': 'application/json' },
  3108. body: JSON.stringify({ disabled })
  3109. });
  3110. if (res.ok) loadFirewall(false);
  3111. } catch (err) {
  3112. showToast('Error', err.message, 'error');
  3113. }
  3114. }
  3115. async function deleteMangleRule(id) {
  3116. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  3117. try {
  3118. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3119. if (res.ok) {
  3120. showToast('Deleted', 'Mangle rule removed', 'success');
  3121. loadFirewall(false);
  3122. }
  3123. } catch (err) {
  3124. showToast('Error', err.message, 'error');
  3125. }
  3126. }
  3127. // ----------------- Address Lists -----------------
  3128. function renderAddressLists() {
  3129. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  3130. const tbody = document.getElementById('addrlist-table-body');
  3131. const empty = document.getElementById('addrlist-empty');
  3132. if (!tbody) return;
  3133. tbody.innerHTML = '';
  3134. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  3135. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries`;
  3136. // Update filter select
  3137. const sel = document.getElementById('addrlist-filter-name');
  3138. if (sel) {
  3139. const cur = sel.value;
  3140. sel.innerHTML = '<option value="">All Lists</option>';
  3141. const set = new Set((state.addressLists || []).map(a => a.name));
  3142. set.forEach(n => {
  3143. const opt = document.createElement('option');
  3144. opt.value = n;
  3145. opt.innerText = n;
  3146. if (n === cur) opt.selected = true;
  3147. sel.appendChild(opt);
  3148. });
  3149. }
  3150. if (entries.length === 0) {
  3151. empty?.classList.remove('hidden');
  3152. return;
  3153. }
  3154. empty?.classList.add('hidden');
  3155. entries.forEach((e, idx) => {
  3156. const tr = document.createElement('tr');
  3157. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
  3158. tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
  3159. tr.innerHTML = `
  3160. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  3161. <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>
  3162. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  3163. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  3164. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]">${e.comment || '-'}</td>
  3165. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  3166. <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>
  3167. <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
  3168. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3169. </td>
  3170. `;
  3171. tbody.appendChild(tr);
  3172. });
  3173. }
  3174. function openAddAddrListModal() {
  3175. document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
  3176. document.getElementById('addrlist-modal-id').value = '';
  3177. document.getElementById('addrlist-modal-name').value = '';
  3178. document.getElementById('addrlist-modal-addr').value = '';
  3179. document.getElementById('addrlist-modal-comment').value = '';
  3180. document.getElementById('addrlist-modal-disabled').checked = false;
  3181. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  3182. if (submitBtn) submitBtn.innerText = 'Add to List';
  3183. document.getElementById('addrlist-modal').classList.remove('hidden');
  3184. }
  3185. function openEditAddrListModal(id) {
  3186. const e = (state.addressLists || []).find(item => item.id === id);
  3187. if (!e) return;
  3188. document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
  3189. document.getElementById('addrlist-modal-id').value = e.id;
  3190. document.getElementById('addrlist-modal-name').value = e.name;
  3191. document.getElementById('addrlist-modal-addr').value = e.address;
  3192. document.getElementById('addrlist-modal-comment').value = e.comment || '';
  3193. document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
  3194. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  3195. if (submitBtn) submitBtn.innerText = 'Save Changes';
  3196. document.getElementById('addrlist-modal').classList.remove('hidden');
  3197. }
  3198. function closeAddrListModal() {
  3199. document.getElementById('addrlist-modal').classList.add('hidden');
  3200. }
  3201. async function submitSaveAddrList(e) {
  3202. e.preventDefault();
  3203. const id = document.getElementById('addrlist-modal-id').value;
  3204. const name = document.getElementById('addrlist-modal-name').value.trim();
  3205. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  3206. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  3207. const disabled = document.getElementById('addrlist-modal-disabled').checked;
  3208. try {
  3209. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  3210. method: 'POST',
  3211. headers: { 'Content-Type': 'application/json' },
  3212. body: JSON.stringify({ id, name, address: addr, comment, disabled })
  3213. });
  3214. if (res.ok) {
  3215. showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
  3216. closeAddrListModal();
  3217. loadFirewall(false);
  3218. } else {
  3219. const err = await res.json();
  3220. showToast('Error', err.message || 'Failed to save address list', 'error');
  3221. }
  3222. } catch (err) {
  3223. showToast('Error', err.message, 'error');
  3224. }
  3225. }
  3226. async function toggleAddrListState(id, disabled) {
  3227. try {
  3228. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
  3229. method: 'POST',
  3230. headers: { 'Content-Type': 'application/json' },
  3231. body: JSON.stringify({ disabled })
  3232. });
  3233. if (res.ok) {
  3234. loadFirewall(false);
  3235. }
  3236. } catch (err) {
  3237. showToast('Error', err.message, 'error');
  3238. }
  3239. }
  3240. async function deleteAddrList(id) {
  3241. if (!confirm('Are you sure you want to delete this address list item?')) return;
  3242. try {
  3243. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3244. if (res.ok) {
  3245. showToast('Deleted', 'Address list item removed', 'info');
  3246. loadFirewall(false);
  3247. }
  3248. } catch (err) {
  3249. showToast('Error', err.message, 'error');
  3250. }
  3251. }
  3252. // ----------------- Geo-Location IP Management -----------------
  3253. async function loadGeoIP() {
  3254. try {
  3255. const [statusRes, countriesRes] = await Promise.all([
  3256. fetch(`${API_BASE}/firewall/geoip/status`),
  3257. fetch(`${API_BASE}/firewall/geoip/countries`)
  3258. ]);
  3259. if (statusRes.ok) state.geoStatus = await statusRes.json();
  3260. if (countriesRes.ok) state.geoCountries = await countriesRes.json();
  3261. updateGeoHeader();
  3262. renderGeoCountries();
  3263. } catch (err) {
  3264. console.error('Failed to load GeoIP:', err);
  3265. }
  3266. }
  3267. function getGeoUsageMap() {
  3268. const usage = {};
  3269. const checkRule = (r, type) => {
  3270. ['src_geoip', 'dst_geoip'].forEach(field => {
  3271. let val = (r && r[field]) || '';
  3272. let code = val.replace(/^!/, '').replace(/^geo:/, '').replace(/^geo_/, '').toUpperCase().trim();
  3273. if (code) {
  3274. if (!usage[code]) usage[code] = [];
  3275. const label = `${type} #${r.priority !== undefined ? r.priority : (r.id || '')}`;
  3276. if (!usage[code].includes(label)) usage[code].push(label);
  3277. }
  3278. });
  3279. };
  3280. (state.filterRules || []).forEach(r => checkRule(r, 'Filter'));
  3281. (state.natRules || []).forEach(r => checkRule(r, 'NAT'));
  3282. (state.mangleRules || []).forEach(r => checkRule(r, 'Mangle'));
  3283. return usage;
  3284. }
  3285. function updateGeoHeader() {
  3286. const s = state.geoStatus || {};
  3287. const statusBadge = document.getElementById('geo-status-badge');
  3288. if (statusBadge) {
  3289. statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
  3290. statusBadge.className = s.auto_update
  3291. ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
  3292. : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
  3293. }
  3294. const intervalLabel = document.getElementById('geo-interval-label');
  3295. if (intervalLabel) {
  3296. intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
  3297. }
  3298. const usageMap = getGeoUsageMap();
  3299. const inUseCount = Object.keys(usageMap).length;
  3300. const activeCountEl = document.getElementById('geo-stat-active-countries');
  3301. if (activeCountEl) activeCountEl.innerText = inUseCount.toLocaleString();
  3302. const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
  3303. if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
  3304. const lastSyncEl = document.getElementById('geo-stat-last-sync');
  3305. if (lastSyncEl) {
  3306. if (s.last_updated && !s.last_updated.startsWith('0001')) {
  3307. const d = new Date(s.last_updated);
  3308. lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  3309. } else {
  3310. lastSyncEl.innerText = 'Never (Sync Pending)';
  3311. }
  3312. }
  3313. const nextSyncEl = document.getElementById('geo-stat-next-sync');
  3314. if (nextSyncEl) {
  3315. if (s.next_update && !s.next_update.startsWith('0001')) {
  3316. const d = new Date(s.next_update);
  3317. nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  3318. } else {
  3319. nextSyncEl.innerText = '-';
  3320. }
  3321. }
  3322. const badge = document.getElementById('fw-badge-geo');
  3323. if (badge) badge.innerText = inUseCount || (state.geoCountries || []).filter(c => c.subnet_count > 0).length || 0;
  3324. }
  3325. function renderGeoCountries() {
  3326. const tbody = document.getElementById('geo-table-body');
  3327. const empty = document.getElementById('geo-empty');
  3328. if (!tbody) return;
  3329. tbody.innerHTML = '';
  3330. const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
  3331. const continent = document.getElementById('geo-continent-filter')?.value || '';
  3332. const inUseOnly = document.getElementById('geo-filter-inuse-only')?.checked;
  3333. const cachedOnly = document.getElementById('geo-filter-cached-only')?.checked;
  3334. const usageMap = getGeoUsageMap();
  3335. const countries = (state.geoCountries || []).filter(c => {
  3336. const isUsed = !!usageMap[c.code];
  3337. if (inUseOnly && !isUsed) return false;
  3338. if (cachedOnly && (!c.subnet_count || c.subnet_count === 0)) return false;
  3339. if (continent && c.continent !== continent) return false;
  3340. if (q) {
  3341. const matchCode = c.code.toLowerCase().includes(q);
  3342. const matchName = c.name.toLowerCase().includes(q);
  3343. if (!matchCode && !matchName) return false;
  3344. }
  3345. return true;
  3346. });
  3347. if (countries.length === 0) {
  3348. empty?.classList.remove('hidden');
  3349. return;
  3350. }
  3351. empty?.classList.add('hidden');
  3352. countries.forEach(c => {
  3353. const tr = document.createElement('tr');
  3354. const isUsed = !!usageMap[c.code];
  3355. const rulesUsing = usageMap[c.code] || [];
  3356. tr.className = `hover:bg-slate-800/40 transition text-xs ${isUsed ? 'bg-emerald-950/20' : ''}`;
  3357. let statusHtml = '';
  3358. if (isUsed) {
  3359. 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>`;
  3360. } else if (c.subnet_count > 0) {
  3361. 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>';
  3362. } else {
  3363. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-slate-500 bg-slate-800/60">READY</span>';
  3364. }
  3365. tr.innerHTML = `
  3366. <td class="py-2.5 px-3 text-center">
  3367. <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'}">
  3368. ${c.code}
  3369. </span>
  3370. </td>
  3371. <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
  3372. <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
  3373. <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
  3374. ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
  3375. </td>
  3376. <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
  3377. <td class="py-2.5 px-3">
  3378. ${statusHtml}
  3379. </td>
  3380. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  3381. <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>
  3382. <button onclick="viewGeoSubnets('${c.code}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
  3383. </td>
  3384. `;
  3385. tbody.appendChild(tr);
  3386. });
  3387. }
  3388. function quickFilterGeo(preset) {
  3389. const searchInput = document.getElementById('geo-search-input');
  3390. const continentSel = document.getElementById('geo-continent-filter');
  3391. const inUseCheck = document.getElementById('geo-filter-inuse-only');
  3392. const cachedCheck = document.getElementById('geo-filter-cached-only');
  3393. if (searchInput) searchInput.value = '';
  3394. if (continentSel) continentSel.value = '';
  3395. if (inUseCheck) inUseCheck.checked = false;
  3396. if (cachedCheck) cachedCheck.checked = false;
  3397. if (preset === 'GR') {
  3398. if (searchInput) searchInput.value = 'Greece';
  3399. } else if (preset === 'Europe') {
  3400. if (continentSel) continentSel.value = 'Europe';
  3401. } else if (preset === 'HIGHRISK') {
  3402. if (searchInput) searchInput.value = 'China';
  3403. }
  3404. renderGeoCountries();
  3405. }
  3406. async function toggleGeoCountry(code, enabled) {
  3407. try {
  3408. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
  3409. method: 'POST',
  3410. headers: { 'Content-Type': 'application/json' },
  3411. body: JSON.stringify({ enabled })
  3412. });
  3413. if (res.ok) {
  3414. showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
  3415. loadGeoIP();
  3416. } else {
  3417. const err = await res.json();
  3418. showToast('Error', err.message || 'Failed to toggle country', 'error');
  3419. }
  3420. } catch (err) {
  3421. showToast('Error', err.message, 'error');
  3422. }
  3423. }
  3424. async function updateGeoCountry(code) {
  3425. try {
  3426. showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
  3427. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
  3428. if (res.ok) {
  3429. const data = await res.json();
  3430. showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
  3431. loadGeoIP();
  3432. } else {
  3433. const err = await res.json();
  3434. showToast('Sync Error', err.message || 'Failed to sync country', 'error');
  3435. }
  3436. } catch (err) {
  3437. showToast('Error', err.message, 'error');
  3438. }
  3439. }
  3440. async function triggerGeoUpdateNow() {
  3441. const spinner = document.getElementById('geo-update-spinner');
  3442. if (spinner) spinner.classList.remove('hidden');
  3443. try {
  3444. const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
  3445. if (res.ok) {
  3446. showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
  3447. setTimeout(() => {
  3448. loadGeoIP();
  3449. if (spinner) spinner.classList.add('hidden');
  3450. }, 2500);
  3451. } else {
  3452. const err = await res.json();
  3453. showToast('Notice', err.message || 'Update in progress', 'info');
  3454. if (spinner) spinner.classList.add('hidden');
  3455. }
  3456. } catch (err) {
  3457. showToast('Error', err.message, 'error');
  3458. if (spinner) spinner.classList.add('hidden');
  3459. }
  3460. }
  3461. async function applyGeoPreset(preset) {
  3462. try {
  3463. const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
  3464. method: 'POST',
  3465. headers: { 'Content-Type': 'application/json' },
  3466. body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
  3467. });
  3468. if (res.ok) {
  3469. showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
  3470. loadGeoIP();
  3471. }
  3472. } catch (err) {
  3473. showToast('Error', err.message, 'error');
  3474. }
  3475. }
  3476. function openGeoIntervalModal() {
  3477. const s = state.geoStatus || {};
  3478. document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
  3479. const sel = document.getElementById('geo-cfg-interval');
  3480. const customBox = document.getElementById('geo-cfg-custom-box');
  3481. const customHoursInput = document.getElementById('geo-cfg-custom-hours');
  3482. const curHours = s.interval_hours || 24;
  3483. const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
  3484. if (matchOption) {
  3485. sel.value = String(curHours);
  3486. customBox.classList.add('hidden');
  3487. } else {
  3488. sel.value = 'custom';
  3489. customHoursInput.value = curHours;
  3490. customBox.classList.remove('hidden');
  3491. }
  3492. document.getElementById('geo-interval-modal').classList.remove('hidden');
  3493. }
  3494. function closeGeoIntervalModal() {
  3495. document.getElementById('geo-interval-modal').classList.add('hidden');
  3496. }
  3497. function toggleCustomGeoInterval() {
  3498. const val = document.getElementById('geo-cfg-interval').value;
  3499. const customBox = document.getElementById('geo-cfg-custom-box');
  3500. if (val === 'custom') {
  3501. customBox.classList.remove('hidden');
  3502. } else {
  3503. customBox.classList.add('hidden');
  3504. }
  3505. }
  3506. async function submitGeoIntervalSettings(e) {
  3507. e.preventDefault();
  3508. const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
  3509. const intervalVal = document.getElementById('geo-cfg-interval').value;
  3510. let hours = 24;
  3511. if (intervalVal === 'custom') {
  3512. hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
  3513. } else {
  3514. hours = parseInt(intervalVal, 10) || 24;
  3515. }
  3516. try {
  3517. const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
  3518. method: 'POST',
  3519. headers: { 'Content-Type': 'application/json' },
  3520. body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
  3521. });
  3522. if (res.ok) {
  3523. showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
  3524. closeGeoIntervalModal();
  3525. loadGeoIP();
  3526. } else {
  3527. const err = await res.json();
  3528. showToast('Error', err.message || 'Failed to save schedule', 'error');
  3529. }
  3530. } catch (err) {
  3531. showToast('Error', err.message, 'error');
  3532. }
  3533. }
  3534. async function viewGeoSubnets(code, name) {
  3535. if (!name) {
  3536. const found = (state.geoCountries || []).find(x => x.code === code);
  3537. name = found ? found.name : code;
  3538. }
  3539. document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
  3540. document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
  3541. const listEl = document.getElementById('geo-subnets-list');
  3542. listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
  3543. document.getElementById('geo-subnets-modal').classList.remove('hidden');
  3544. try {
  3545. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
  3546. if (res.ok) {
  3547. const data = await res.json();
  3548. const subnets = data.subnets || [];
  3549. if (subnets.length === 0) {
  3550. listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
  3551. } else {
  3552. listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
  3553. }
  3554. } else {
  3555. listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
  3556. }
  3557. } catch (err) {
  3558. listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
  3559. }
  3560. }
  3561. function closeGeoSubnetsModal() {
  3562. document.getElementById('geo-subnets-modal').classList.add('hidden');
  3563. }
  3564. // ----------------- Active Connections Tracking -----------------
  3565. async function loadConnections() {
  3566. try {
  3567. const res = await fetch(`${API_BASE}/firewall/connections`);
  3568. const data = await res.json();
  3569. state.connections = Array.isArray(data) ? data : [];
  3570. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  3571. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  3572. renderConnections();
  3573. } catch (err) {
  3574. console.error('Failed to load connections:', err);
  3575. }
  3576. }
  3577. function renderConnections() {
  3578. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  3579. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  3580. const tbody = document.getElementById('conns-table-body');
  3581. const empty = document.getElementById('conns-empty');
  3582. if (!tbody) return;
  3583. tbody.innerHTML = '';
  3584. const conns = (state.connections || []).filter(c => {
  3585. if (protoFilter && c.protocol !== protoFilter) return false;
  3586. if (search) {
  3587. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  3588. if (!line.includes(search)) return false;
  3589. }
  3590. return true;
  3591. });
  3592. if (conns.length === 0) {
  3593. empty?.classList.remove('hidden');
  3594. return;
  3595. }
  3596. empty?.classList.add('hidden');
  3597. conns.slice(0, 150).forEach(c => {
  3598. const tr = document.createElement('tr');
  3599. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  3600. let stateColor = 'text-slate-400';
  3601. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  3602. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  3603. tr.innerHTML = `
  3604. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  3605. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  3606. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  3607. <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>
  3608. <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>
  3609. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  3610. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  3611. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  3612. <td class="py-2.5 px-3 text-right font-sans">
  3613. <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>
  3614. </td>
  3615. `;
  3616. tbody.appendChild(tr);
  3617. });
  3618. }
  3619. async function killConnection(protocol, src, sport, dst, dport) {
  3620. try {
  3621. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  3622. method: 'POST',
  3623. headers: { 'Content-Type': 'application/json' },
  3624. body: JSON.stringify({ protocol, src, sport, dst, dport })
  3625. });
  3626. if (res.ok) {
  3627. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  3628. loadConnections();
  3629. }
  3630. } catch (err) {
  3631. showToast('Error', err.message, 'error');
  3632. }
  3633. }
  3634. async function resetFirewallCounters() {
  3635. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  3636. try {
  3637. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  3638. if (res.ok) {
  3639. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  3640. loadFirewall(false);
  3641. }
  3642. } catch (err) {
  3643. showToast('Error', err.message, 'error');
  3644. }
  3645. }
  3646. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  3647. function switchRoutesSubTab(tab) {
  3648. state.routesSubTab = tab;
  3649. const tabs = ['routes', 'rules', 'tables'];
  3650. tabs.forEach(t => {
  3651. const panel = document.getElementById(`routes-subtab-${t}`);
  3652. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  3653. if (panel) {
  3654. if (t === tab) panel.classList.remove('hidden');
  3655. else panel.classList.add('hidden');
  3656. }
  3657. if (btn) {
  3658. if (t === tab) {
  3659. 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';
  3660. } else {
  3661. 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';
  3662. }
  3663. }
  3664. });
  3665. }
  3666. async function loadRoutes() {
  3667. try {
  3668. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  3669. fetch(`${API_BASE}/routes`),
  3670. fetch(`${API_BASE}/routing/rules`),
  3671. fetch(`${API_BASE}/routing/tables`)
  3672. ]);
  3673. if (routesRes.ok) state.routes = await routesRes.json();
  3674. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  3675. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  3676. const bRoutes = document.getElementById('routes-badge-routes');
  3677. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  3678. const bRules = document.getElementById('routes-badge-rules');
  3679. if (bRules) bRules.innerText = (state.policyRules || []).length;
  3680. const bTables = document.getElementById('routes-badge-tables');
  3681. if (bTables) bTables.innerText = (state.routingTables || []).length;
  3682. const bRoutesCount = document.getElementById('badge-routes-count');
  3683. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  3684. renderRoutesList();
  3685. renderPolicyRules();
  3686. renderRoutingTables();
  3687. } catch (err) {
  3688. console.error('Failed to load routing:', err);
  3689. }
  3690. }
  3691. function renderRoutesList() {
  3692. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  3693. const tbody = document.getElementById('routes-table-body');
  3694. const empty = document.getElementById('routes-empty');
  3695. if (!tbody) return;
  3696. tbody.innerHTML = '';
  3697. // Update table filter select
  3698. const sel = document.getElementById('routes-filter-table');
  3699. if (sel) {
  3700. const cur = sel.value;
  3701. sel.innerHTML = '<option value="">All Tables</option>';
  3702. (state.routingTables || []).forEach(t => {
  3703. const opt = document.createElement('option');
  3704. opt.value = t.name;
  3705. opt.innerText = t.name;
  3706. if (t.name === cur) opt.selected = true;
  3707. sel.appendChild(opt);
  3708. });
  3709. }
  3710. const routes = (state.routes || []).filter(r => !tableFilter || r.routing_table === tableFilter);
  3711. document.getElementById('routes-count-badge').innerText = `${routes.length} Routes`;
  3712. if (routes.length === 0) {
  3713. empty?.classList.remove('hidden');
  3714. return;
  3715. }
  3716. empty?.classList.add('hidden');
  3717. routes.forEach(r => {
  3718. const tr = document.createElement('tr');
  3719. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  3720. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  3721. // MikroTik Flags string: D=Dynamic, A=Active, C=Connect, S=Static, X=Disabled
  3722. let flags = '';
  3723. if (r.dynamic) flags += 'D';
  3724. if (r.active) flags += 'A';
  3725. if (r.connect) flags += 'C';
  3726. if (r.static) flags += 'S';
  3727. if (r.disabled) flags += 'X';
  3728. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  3729. tr.innerHTML = `
  3730. <td class="py-2.5 px-3 text-center">
  3731. <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'}">
  3732. ${flags || '-'}
  3733. </span>
  3734. </td>
  3735. <td class="py-2.5 px-3 font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${r.dst_address}</td>
  3736. <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>
  3737. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  3738. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  3739. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  3740. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  3741. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  3742. ${r.static ? `
  3743. <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>
  3744. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  3745. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3746. ` : `
  3747. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  3748. `}
  3749. </td>
  3750. `;
  3751. tbody.appendChild(tr);
  3752. });
  3753. }
  3754. function openAddRouteModal() {
  3755. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  3756. document.getElementById('route-modal-id').value = '';
  3757. document.getElementById('route-modal-old-dst').value = '';
  3758. document.getElementById('route-modal-old-gw').value = '';
  3759. document.getElementById('route-modal-old-distance').value = '';
  3760. document.getElementById('route-modal-old-table').value = '';
  3761. document.getElementById('route-modal-old-iface').value = '';
  3762. const dstInput = document.getElementById('route-modal-dst');
  3763. const gwInput = document.getElementById('route-modal-gw');
  3764. const distInput = document.getElementById('route-modal-distance');
  3765. const ifaceSelect = document.getElementById('route-modal-iface');
  3766. const tableSelect = document.getElementById('route-modal-table');
  3767. const commentInput = document.getElementById('route-modal-comment');
  3768. const disCheck = document.getElementById('route-modal-disabled');
  3769. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  3770. dstInput.disabled = false;
  3771. dstInput.value = '0.0.0.0/0';
  3772. gwInput.disabled = false;
  3773. gwInput.value = '';
  3774. distInput.disabled = false;
  3775. distInput.value = '1';
  3776. ifaceSelect.disabled = false;
  3777. tableSelect.disabled = false;
  3778. commentInput.disabled = false;
  3779. commentInput.value = '';
  3780. disCheck.disabled = false;
  3781. disCheck.checked = false;
  3782. if (saveBtn) saveBtn.classList.remove('hidden');
  3783. populateInterfaceSelect('route-modal-iface');
  3784. // Populate tables
  3785. tableSelect.innerHTML = '';
  3786. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  3787. const opt = document.createElement('option');
  3788. opt.value = t.name;
  3789. opt.innerText = t.name;
  3790. if (t.name === 'main') opt.selected = true;
  3791. tableSelect.appendChild(opt);
  3792. });
  3793. document.getElementById('route-modal').classList.remove('hidden');
  3794. }
  3795. function openEditRouteModal(id) {
  3796. const r = (state.routes || []).find(route => route.id === id);
  3797. if (!r) return;
  3798. const isStatic = !!r.static;
  3799. document.getElementById('route-modal-title').innerText = isStatic
  3800. ? `Edit Route: ${r.dst_address}`
  3801. : `Route Properties (Read Only): ${r.dst_address}`;
  3802. document.getElementById('route-modal-id').value = r.id;
  3803. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  3804. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  3805. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  3806. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  3807. document.getElementById('route-modal-old-iface').value = r.interface || '';
  3808. const dstInput = document.getElementById('route-modal-dst');
  3809. const gwInput = document.getElementById('route-modal-gw');
  3810. const distInput = document.getElementById('route-modal-distance');
  3811. const ifaceSelect = document.getElementById('route-modal-iface');
  3812. const tableSelect = document.getElementById('route-modal-table');
  3813. const commentInput = document.getElementById('route-modal-comment');
  3814. const disCheck = document.getElementById('route-modal-disabled');
  3815. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  3816. dstInput.value = r.dst_address;
  3817. gwInput.value = r.gateway || '';
  3818. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  3819. commentInput.value = r.comment || '';
  3820. disCheck.checked = !!r.disabled;
  3821. dstInput.disabled = !isStatic;
  3822. gwInput.disabled = !isStatic;
  3823. distInput.disabled = !isStatic;
  3824. ifaceSelect.disabled = !isStatic;
  3825. tableSelect.disabled = !isStatic;
  3826. commentInput.disabled = !isStatic;
  3827. disCheck.disabled = !isStatic;
  3828. if (saveBtn) {
  3829. if (isStatic) {
  3830. saveBtn.classList.remove('hidden');
  3831. } else {
  3832. saveBtn.classList.add('hidden');
  3833. }
  3834. }
  3835. populateInterfaceSelect('route-modal-iface', r.interface);
  3836. tableSelect.innerHTML = '';
  3837. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  3838. const opt = document.createElement('option');
  3839. opt.value = t.name;
  3840. opt.innerText = t.name;
  3841. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  3842. tableSelect.appendChild(opt);
  3843. });
  3844. document.getElementById('route-modal').classList.remove('hidden');
  3845. }
  3846. function closeRouteModal() {
  3847. document.getElementById('route-modal').classList.add('hidden');
  3848. }
  3849. async function submitSaveRoute(e) {
  3850. e.preventDefault();
  3851. const id = document.getElementById('route-modal-id').value;
  3852. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  3853. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  3854. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  3855. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  3856. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  3857. const dst = document.getElementById('route-modal-dst').value.trim();
  3858. const gw = document.getElementById('route-modal-gw').value.trim();
  3859. const table = document.getElementById('route-modal-table').value;
  3860. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  3861. const iface = document.getElementById('route-modal-iface').value;
  3862. const comment = document.getElementById('route-modal-comment').value.trim();
  3863. const disabled = document.getElementById('route-modal-disabled').checked;
  3864. if (!dst) {
  3865. showToast('Error', 'Destination address is required', 'error');
  3866. return;
  3867. }
  3868. if (!gw && !iface) {
  3869. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  3870. return;
  3871. }
  3872. const payload = {
  3873. id,
  3874. old_dst_address: oldDst,
  3875. old_gateway: oldGw,
  3876. old_routing_table: oldTable,
  3877. old_interface: oldIface,
  3878. dst_address: dst,
  3879. gateway: gw || iface,
  3880. routing_table: table,
  3881. distance,
  3882. interface: iface,
  3883. comment,
  3884. disabled
  3885. };
  3886. if (oldDistStr !== undefined && oldDistStr !== '') {
  3887. payload.old_distance = parseInt(oldDistStr, 10);
  3888. }
  3889. try {
  3890. const res = await fetch(`${API_BASE}/routes`, {
  3891. method: 'POST',
  3892. headers: { 'Content-Type': 'application/json' },
  3893. body: JSON.stringify(payload)
  3894. });
  3895. if (res.ok) {
  3896. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  3897. closeRouteModal();
  3898. loadRoutes();
  3899. } else {
  3900. const err = await res.json();
  3901. showToast('Error', err.message || 'Failed to save route', 'error');
  3902. }
  3903. } catch (err) {
  3904. showToast('Error', err.message, 'error');
  3905. }
  3906. }
  3907. async function toggleRouteState(id, disabled) {
  3908. try {
  3909. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  3910. method: 'POST',
  3911. headers: { 'Content-Type': 'application/json' },
  3912. body: JSON.stringify({ disabled })
  3913. });
  3914. if (res.ok) loadRoutes();
  3915. } catch (err) {
  3916. showToast('Error', err.message, 'error');
  3917. }
  3918. }
  3919. async function deleteRoute(id) {
  3920. if (!confirm('Are you sure you want to delete this route?')) return;
  3921. try {
  3922. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3923. if (res.ok) {
  3924. showToast('Deleted', 'Route removed', 'success');
  3925. loadRoutes();
  3926. }
  3927. } catch (err) {
  3928. showToast('Error', err.message, 'error');
  3929. }
  3930. }
  3931. // ----------------- Policy Rules (/ip route rule) -----------------
  3932. function renderPolicyRules() {
  3933. const tbody = document.getElementById('rules-table-body');
  3934. const empty = document.getElementById('rules-empty');
  3935. if (!tbody) return;
  3936. tbody.innerHTML = '';
  3937. const rules = state.policyRules || [];
  3938. document.getElementById('rules-count-badge').innerText = `${rules.length} Rules`;
  3939. if (rules.length === 0) {
  3940. empty?.classList.remove('hidden');
  3941. return;
  3942. }
  3943. empty?.classList.add('hidden');
  3944. rules.forEach(pr => {
  3945. const tr = document.createElement('tr');
  3946. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  3947. tr.innerHTML = `
  3948. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  3949. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  3950. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  3951. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  3952. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  3953. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  3954. <td class="py-2.5 px-3 text-right font-sans">
  3955. ${pr.priority < 32766 && pr.priority > 0 ? `
  3956. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3957. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  3958. </td>
  3959. `;
  3960. tbody.appendChild(tr);
  3961. });
  3962. }
  3963. function openAddPolicyRuleModal() {
  3964. document.getElementById('prule-modal-pref').value = (state.policyRules || []).length * 10 + 1000;
  3965. document.getElementById('prule-modal-mark').value = '';
  3966. document.getElementById('prule-modal-src').value = '';
  3967. document.getElementById('prule-modal-dst').value = '';
  3968. const sel = document.getElementById('prule-modal-table');
  3969. sel.innerHTML = '';
  3970. (state.routingTables || []).forEach(t => {
  3971. const opt = document.createElement('option');
  3972. opt.value = t.name;
  3973. opt.innerText = t.name;
  3974. sel.appendChild(opt);
  3975. });
  3976. document.getElementById('prule-modal').classList.remove('hidden');
  3977. }
  3978. function closePolicyRuleModal() {
  3979. document.getElementById('prule-modal').classList.add('hidden');
  3980. }
  3981. async function submitSavePolicyRule(e) {
  3982. e.preventDefault();
  3983. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  3984. const mark = document.getElementById('prule-modal-mark').value.trim();
  3985. const src = document.getElementById('prule-modal-src').value.trim();
  3986. const dst = document.getElementById('prule-modal-dst').value.trim();
  3987. const table = document.getElementById('prule-modal-table').value;
  3988. const action = document.getElementById('prule-modal-action').value;
  3989. try {
  3990. const res = await fetch(`${API_BASE}/routing/rules`, {
  3991. method: 'POST',
  3992. headers: { 'Content-Type': 'application/json' },
  3993. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  3994. });
  3995. if (res.ok) {
  3996. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  3997. closePolicyRuleModal();
  3998. loadRoutes();
  3999. } else {
  4000. const err = await res.json();
  4001. showToast('Error', err.message, 'error');
  4002. }
  4003. } catch (err) {
  4004. showToast('Error', err.message, 'error');
  4005. }
  4006. }
  4007. async function deletePolicyRule(id) {
  4008. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  4009. try {
  4010. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4011. if (res.ok) {
  4012. showToast('Rule Removed', 'Policy rule deleted', 'success');
  4013. loadRoutes();
  4014. }
  4015. } catch (err) {
  4016. showToast('Error', err.message, 'error');
  4017. }
  4018. }
  4019. // ----------------- Routing Tables -----------------
  4020. function renderRoutingTables() {
  4021. const tbody = document.getElementById('tables-table-body');
  4022. if (!tbody) return;
  4023. tbody.innerHTML = '';
  4024. (state.routingTables || []).forEach(t => {
  4025. const tr = document.createElement('tr');
  4026. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  4027. tr.innerHTML = `
  4028. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  4029. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  4030. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  4031. `;
  4032. tbody.appendChild(tr);
  4033. });
  4034. }
  4035. function openAddTableModal() {
  4036. document.getElementById('table-modal-name').value = '';
  4037. document.getElementById('table-modal-id').value = '';
  4038. document.getElementById('table-modal-comment').value = '';
  4039. document.getElementById('table-modal').classList.remove('hidden');
  4040. }
  4041. function closeTableModal() {
  4042. document.getElementById('table-modal').classList.add('hidden');
  4043. }
  4044. async function submitSaveTable(e) {
  4045. e.preventDefault();
  4046. const name = document.getElementById('table-modal-name').value.trim();
  4047. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  4048. const comment = document.getElementById('table-modal-comment').value.trim();
  4049. try {
  4050. const res = await fetch(`${API_BASE}/routing/tables`, {
  4051. method: 'POST',
  4052. headers: { 'Content-Type': 'application/json' },
  4053. body: JSON.stringify({ name, table_id: id, comment })
  4054. });
  4055. if (res.ok) {
  4056. showToast('Table Created', `Routing table ${name} registered`, 'success');
  4057. closeTableModal();
  4058. loadRoutes();
  4059. } else {
  4060. const err = await res.json();
  4061. showToast('Error', err.message, 'error');
  4062. }
  4063. } catch (err) {
  4064. showToast('Error', err.message, 'error');
  4065. }
  4066. }
  4067. async function loadDebianConfig() {
  4068. const view = document.getElementById('debian-config-view');
  4069. view.innerText = 'Generating live configuration...';
  4070. try {
  4071. const res = await fetch(`${API_BASE}/debian/config`);
  4072. const data = await res.json();
  4073. view.innerText = data.content || '# Empty config';
  4074. } catch (err) {
  4075. view.innerText = 'Failed to generate Debian network config.';
  4076. }
  4077. }
  4078. async function saveDebianConfig() {
  4079. try {
  4080. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  4081. const data = await res.json();
  4082. if (res.ok) {
  4083. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  4084. loadDebianConfig();
  4085. }
  4086. } catch (err) {
  4087. showToast('Error', err.message, 'error');
  4088. }
  4089. }
  4090. function showToast(title, message, type = 'info') {
  4091. const container = document.getElementById('toast-container');
  4092. const toast = document.createElement('div');
  4093. const borderColors = {
  4094. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  4095. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  4096. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  4097. };
  4098. 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}`;
  4099. toast.innerHTML = `
  4100. <div class="flex-1">
  4101. <div class="font-bold text-xs text-white">${title}</div>
  4102. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${message}</div>
  4103. </div>
  4104. `;
  4105. container.appendChild(toast);
  4106. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  4107. setTimeout(() => {
  4108. toast.classList.add('opacity-0', 'translate-y-2');
  4109. setTimeout(() => toast.remove(), 300);
  4110. }, 4000);
  4111. }
  4112. function formatTraffic(bytesPerSec) {
  4113. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  4114. const kb = bytesPerSec / 1024;
  4115. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  4116. const mb = kb / 1024;
  4117. return `${mb.toFixed(2)} MB/s`;
  4118. }
  4119. function toggleSidebar() {
  4120. const sb = document.getElementById('sidebar');
  4121. sb.classList.toggle('-translate-x-full');
  4122. }
  4123. // ======================== EoIP (Ethernet over IP) ========================
  4124. async function loadEoIP(populate = true) {
  4125. try {
  4126. const res = await fetch(`${API_BASE}/vpn/eoip`);
  4127. const data = await res.json();
  4128. state.eoipTunnels = Array.isArray(data) ? data : [];
  4129. const badge = document.getElementById('eoip-count-badge');
  4130. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  4131. const sideBadge = document.getElementById('badge-eoip-count');
  4132. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  4133. renderEoIPTunnels();
  4134. } catch (err) {
  4135. console.error('Failed to load EoIP:', err);
  4136. }
  4137. }
  4138. function renderEoIPTunnels() {
  4139. const tbody = document.getElementById('eoip-table-body');
  4140. const empty = document.getElementById('eoip-empty');
  4141. if (!tbody) return;
  4142. tbody.innerHTML = '';
  4143. const tunnels = state.eoipTunnels || [];
  4144. if (tunnels.length === 0) {
  4145. empty?.classList.remove('hidden');
  4146. return;
  4147. }
  4148. empty?.classList.add('hidden');
  4149. tunnels.forEach(t => {
  4150. const tr = document.createElement('tr');
  4151. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  4152. tr.innerHTML = `
  4153. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  4154. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  4155. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  4156. <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>
  4157. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  4158. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  4159. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  4160. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  4161. <td class="py-2.5 px-3 font-mono text-[11px]">
  4162. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  4163. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  4164. </td>
  4165. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  4166. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4167. <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>
  4168. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4169. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  4170. </td>
  4171. `;
  4172. tbody.appendChild(tr);
  4173. });
  4174. }
  4175. function openAddEoIPModal() {
  4176. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  4177. document.getElementById('eoip-modal-id').value = '';
  4178. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  4179. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  4180. document.getElementById('eoip-modal-remote').value = '';
  4181. document.getElementById('eoip-modal-ip').value = '';
  4182. document.getElementById('eoip-modal-local').value = '';
  4183. document.getElementById('eoip-modal-mac').value = '';
  4184. document.getElementById('eoip-modal-mtu').value = '1500';
  4185. document.getElementById('eoip-modal-comment').value = '';
  4186. document.getElementById('eoip-modal-clampmss').checked = true;
  4187. document.getElementById('eoip-modal-disabled').checked = false;
  4188. document.getElementById('eoip-modal').classList.remove('hidden');
  4189. }
  4190. function openEditEoIPModal(id) {
  4191. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  4192. if (!t) return;
  4193. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  4194. document.getElementById('eoip-modal-id').value = t.id;
  4195. document.getElementById('eoip-modal-name').value = t.name;
  4196. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  4197. document.getElementById('eoip-modal-remote').value = t.remote_address;
  4198. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  4199. document.getElementById('eoip-modal-local').value = t.local_address || '';
  4200. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  4201. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  4202. document.getElementById('eoip-modal-comment').value = t.comment || '';
  4203. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  4204. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  4205. document.getElementById('eoip-modal').classList.remove('hidden');
  4206. }
  4207. function closeEoIPModal() {
  4208. document.getElementById('eoip-modal').classList.add('hidden');
  4209. }
  4210. async function submitSaveEoIP(e) {
  4211. e.preventDefault();
  4212. const id = document.getElementById('eoip-modal-id').value;
  4213. const name = document.getElementById('eoip-modal-name').value.trim();
  4214. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  4215. const remote = document.getElementById('eoip-modal-remote').value.trim();
  4216. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  4217. const local = document.getElementById('eoip-modal-local').value.trim();
  4218. const mac = document.getElementById('eoip-modal-mac').value.trim();
  4219. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  4220. const comment = document.getElementById('eoip-modal-comment').value.trim();
  4221. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  4222. const disabled = document.getElementById('eoip-modal-disabled').checked;
  4223. try {
  4224. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  4225. method: 'POST',
  4226. headers: { 'Content-Type': 'application/json' },
  4227. body: JSON.stringify({
  4228. id,
  4229. name,
  4230. tunnel_id: tunnelId,
  4231. remote_address: remote,
  4232. ip_address: ipAddress,
  4233. local_address: local,
  4234. mac_address: mac,
  4235. mtu,
  4236. clamp_mss: clampMss,
  4237. comment,
  4238. disabled
  4239. })
  4240. });
  4241. if (res.ok) {
  4242. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  4243. closeEoIPModal();
  4244. loadEoIP(false);
  4245. fetchData(false);
  4246. } else {
  4247. const err = await res.json();
  4248. showToast('Error', err.message, 'error');
  4249. }
  4250. } catch (err) {
  4251. showToast('Error', err.message, 'error');
  4252. }
  4253. }
  4254. async function toggleEoIPState(id, disabled) {
  4255. try {
  4256. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  4257. method: 'POST',
  4258. headers: { 'Content-Type': 'application/json' },
  4259. body: JSON.stringify({ disabled })
  4260. });
  4261. if (res.ok) {
  4262. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  4263. loadEoIP(false);
  4264. fetchData(false);
  4265. }
  4266. } catch (err) {
  4267. showToast('Error', err.message, 'error');
  4268. }
  4269. }
  4270. async function deleteEoIP(id) {
  4271. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  4272. try {
  4273. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4274. if (res.ok) {
  4275. showToast('Deleted', 'EoIP tunnel removed', 'success');
  4276. loadEoIP(false);
  4277. fetchData(false);
  4278. }
  4279. } catch (err) {
  4280. showToast('Error', err.message, 'error');
  4281. }
  4282. }
  4283. // ======================== PPP Central Hub & Servers ========================
  4284. function switchPPPSubTab(tab) {
  4285. state.pppSubTab = tab;
  4286. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  4287. tabs.forEach(t => {
  4288. const panel = document.getElementById(`ppp-subtab-${t}`);
  4289. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  4290. if (panel) {
  4291. if (t === tab) panel.classList.remove('hidden');
  4292. else panel.classList.add('hidden');
  4293. }
  4294. if (btn) {
  4295. if (t === tab) {
  4296. 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';
  4297. } else {
  4298. 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';
  4299. }
  4300. }
  4301. });
  4302. const addBtn = document.getElementById('ppp-primary-add-btn');
  4303. if (addBtn) {
  4304. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  4305. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  4306. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  4307. else addBtn.innerHTML = '<span>Save Config</span>';
  4308. }
  4309. if (tab === 'active') loadPPPSessions();
  4310. }
  4311. function openCurrentPPPModal() {
  4312. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  4313. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  4314. else if (state.pppSubTab === 'active') loadPPPSessions();
  4315. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  4316. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  4317. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  4318. }
  4319. async function loadPPP(populateDropdowns = true) {
  4320. await Promise.all([
  4321. loadPPPSecrets(),
  4322. loadPPPProfiles(),
  4323. loadPPPServers(),
  4324. loadPPPSessions()
  4325. ]);
  4326. }
  4327. async function loadPPPSecrets() {
  4328. try {
  4329. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  4330. const data = await res.json();
  4331. state.pppSecrets = Array.isArray(data) ? data : [];
  4332. const b = document.getElementById('ppp-badge-secrets');
  4333. if (b) b.innerText = state.pppSecrets.length;
  4334. const b2 = document.getElementById('secrets-count-badge');
  4335. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  4336. renderPPPSecrets();
  4337. } catch (err) {
  4338. console.error('Failed to load PPP secrets:', err);
  4339. }
  4340. }
  4341. function renderPPPSecrets() {
  4342. const tbody = document.getElementById('secrets-table-body');
  4343. const empty = document.getElementById('secrets-empty');
  4344. if (!tbody) return;
  4345. tbody.innerHTML = '';
  4346. const secrets = state.pppSecrets || [];
  4347. if (secrets.length === 0) {
  4348. empty?.classList.remove('hidden');
  4349. return;
  4350. }
  4351. empty?.classList.add('hidden');
  4352. secrets.forEach(s => {
  4353. const tr = document.createElement('tr');
  4354. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  4355. tr.innerHTML = `
  4356. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  4357. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  4358. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  4359. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  4360. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  4361. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  4362. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  4363. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4364. <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>
  4365. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4366. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  4367. </td>
  4368. `;
  4369. tbody.appendChild(tr);
  4370. });
  4371. }
  4372. async function loadPPPProfiles() {
  4373. try {
  4374. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  4375. const data = await res.json();
  4376. state.pppProfiles = Array.isArray(data) ? data : [];
  4377. const b = document.getElementById('ppp-badge-profiles');
  4378. if (b) b.innerText = state.pppProfiles.length;
  4379. const b2 = document.getElementById('profiles-count-badge');
  4380. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  4381. // Populate profile selects across modals
  4382. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  4383. selects.forEach(sid => {
  4384. const el = document.getElementById(sid);
  4385. if (!el) return;
  4386. const cur = el.value;
  4387. el.innerHTML = '';
  4388. state.pppProfiles.forEach(p => {
  4389. const opt = document.createElement('option');
  4390. opt.value = p.name;
  4391. opt.innerText = `${p.name} (${p.remote_address})`;
  4392. if (p.name === cur) opt.selected = true;
  4393. el.appendChild(opt);
  4394. });
  4395. });
  4396. renderPPPProfiles();
  4397. } catch (err) {
  4398. console.error('Failed to load PPP profiles:', err);
  4399. }
  4400. }
  4401. function renderPPPProfiles() {
  4402. const tbody = document.getElementById('profiles-table-body');
  4403. if (!tbody) return;
  4404. tbody.innerHTML = '';
  4405. (state.pppProfiles || []).forEach(p => {
  4406. const isDefault = p.name.startsWith('default');
  4407. const tr = document.createElement('tr');
  4408. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  4409. tr.innerHTML = `
  4410. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  4411. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  4412. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  4413. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  4414. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  4415. <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>
  4416. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  4417. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  4418. ${!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>`}
  4419. </td>
  4420. `;
  4421. tbody.appendChild(tr);
  4422. });
  4423. }
  4424. async function loadPPPServers() {
  4425. try {
  4426. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  4427. fetch(`${API_BASE}/vpn/servers/pppoe`),
  4428. fetch(`${API_BASE}/vpn/servers/pptp`),
  4429. fetch(`${API_BASE}/vpn/servers/l2tp`),
  4430. fetch(`${API_BASE}/vpn/servers/ipsec`)
  4431. ]);
  4432. if (pppoeRes.ok) {
  4433. state.pppoeServer = await pppoeRes.json();
  4434. const s = state.pppoeServer;
  4435. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  4436. document.getElementById('pppoe-server-name').value = s.service_name || 'proxmox-pppoe';
  4437. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  4438. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  4439. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  4440. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  4441. const pill = document.getElementById('pppoe-server-status-pill');
  4442. if (pill) {
  4443. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  4444. 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';
  4445. }
  4446. setDotBadge('ppp-badge-pppoe-state', s.running);
  4447. }
  4448. if (pptpRes.ok) {
  4449. state.pptpServer = await pptpRes.json();
  4450. const s = state.pptpServer;
  4451. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  4452. document.getElementById('pptp-server-port').value = s.port || 1723;
  4453. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  4454. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  4455. const pill = document.getElementById('pptp-server-status-pill');
  4456. if (pill) {
  4457. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  4458. 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';
  4459. }
  4460. setDotBadge('ppp-badge-pptp-state', s.running);
  4461. }
  4462. if (l2tpRes.ok) {
  4463. state.l2tpServer = await l2tpRes.json();
  4464. const s = state.l2tpServer;
  4465. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  4466. document.getElementById('l2tp-server-port').value = s.port || 1701;
  4467. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  4468. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  4469. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  4470. const pill = document.getElementById('l2tp-server-status-pill');
  4471. if (pill) {
  4472. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  4473. 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';
  4474. }
  4475. setDotBadge('ppp-badge-l2tp-state', s.running);
  4476. }
  4477. if (ipsecRes.ok) {
  4478. state.ipsecServer = await ipsecRes.json();
  4479. const s = state.ipsecServer;
  4480. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  4481. if (modalEn) modalEn.checked = !!s.enabled;
  4482. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  4483. if (modalPsk) modalPsk.value = s.preshared_key || '';
  4484. const modalPool = document.getElementById('modal-ipsec-server-pool');
  4485. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  4486. const modalDns = document.getElementById('modal-ipsec-server-dns');
  4487. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  4488. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  4489. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  4490. const pill = document.getElementById('modal-ipsec-server-status');
  4491. if (pill) {
  4492. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  4493. 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';
  4494. }
  4495. }
  4496. } catch (err) {
  4497. console.error('Failed to load VPN servers:', err);
  4498. }
  4499. }
  4500. async function loadPPPSessions() {
  4501. try {
  4502. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  4503. const data = await res.json();
  4504. state.pppActiveSessions = Array.isArray(data) ? data : [];
  4505. const b = document.getElementById('ppp-badge-active');
  4506. if (b) b.innerText = state.pppActiveSessions.length;
  4507. const sideB = document.getElementById('badge-ppp-sessions');
  4508. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  4509. renderPPPSessions();
  4510. } catch (err) {
  4511. console.error('Failed to load active PPP sessions:', err);
  4512. }
  4513. }
  4514. function renderPPPSessions() {
  4515. const tbody = document.getElementById('active-ppp-table-body');
  4516. const empty = document.getElementById('active-ppp-empty');
  4517. if (!tbody) return;
  4518. tbody.innerHTML = '';
  4519. const list = state.pppActiveSessions || [];
  4520. if (list.length === 0) {
  4521. empty?.classList.remove('hidden');
  4522. return;
  4523. }
  4524. empty?.classList.add('hidden');
  4525. list.forEach(s => {
  4526. const tr = document.createElement('tr');
  4527. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  4528. tr.innerHTML = `
  4529. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  4530. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  4531. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  4532. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  4533. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  4534. <td class="py-2.5 px-3 text-[11px]">
  4535. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  4536. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  4537. </td>
  4538. <td class="py-2.5 px-3 text-right font-sans">
  4539. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  4540. </td>
  4541. `;
  4542. tbody.appendChild(tr);
  4543. });
  4544. }
  4545. async function disconnectPPPSession(iface) {
  4546. if (!confirm(`Disconnect session ${iface}?`)) return;
  4547. try {
  4548. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  4549. if (res.ok) {
  4550. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  4551. loadPPPSessions();
  4552. }
  4553. } catch (err) {
  4554. showToast('Error', err.message, 'error');
  4555. }
  4556. }
  4557. // PPP Secret Modal handlers
  4558. function openAddPPPSecretModal() {
  4559. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  4560. document.getElementById('secret-modal-id').value = '';
  4561. document.getElementById('secret-modal-name').value = '';
  4562. document.getElementById('secret-modal-password').value = '';
  4563. document.getElementById('secret-modal-service').value = 'any';
  4564. document.getElementById('secret-modal-profile').value = 'default';
  4565. document.getElementById('secret-modal-local').value = '';
  4566. document.getElementById('secret-modal-remote').value = '';
  4567. document.getElementById('secret-modal-comment').value = '';
  4568. document.getElementById('secret-modal-disabled').checked = false;
  4569. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  4570. }
  4571. function openEditPPPSecretModal(id) {
  4572. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  4573. if (!s) return;
  4574. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  4575. document.getElementById('secret-modal-id').value = s.id;
  4576. document.getElementById('secret-modal-name').value = s.name;
  4577. document.getElementById('secret-modal-password').value = s.password;
  4578. document.getElementById('secret-modal-service').value = s.service || 'any';
  4579. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  4580. document.getElementById('secret-modal-local').value = s.local_address || '';
  4581. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  4582. document.getElementById('secret-modal-comment').value = s.comment || '';
  4583. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  4584. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  4585. }
  4586. function closePPPSecretModal() {
  4587. document.getElementById('ppp-secret-modal').classList.add('hidden');
  4588. }
  4589. async function submitSavePPPSecret(e) {
  4590. e.preventDefault();
  4591. const id = document.getElementById('secret-modal-id').value;
  4592. const name = document.getElementById('secret-modal-name').value.trim();
  4593. const password = document.getElementById('secret-modal-password').value.trim();
  4594. const service = document.getElementById('secret-modal-service').value;
  4595. const profile = document.getElementById('secret-modal-profile').value;
  4596. const local = document.getElementById('secret-modal-local').value.trim();
  4597. const remote = document.getElementById('secret-modal-remote').value.trim();
  4598. const comment = document.getElementById('secret-modal-comment').value.trim();
  4599. const disabled = document.getElementById('secret-modal-disabled').checked;
  4600. try {
  4601. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  4602. method: 'POST',
  4603. headers: { 'Content-Type': 'application/json' },
  4604. body: JSON.stringify({
  4605. id,
  4606. name,
  4607. password,
  4608. service,
  4609. profile,
  4610. local_address: local,
  4611. remote_address: remote,
  4612. comment,
  4613. disabled
  4614. })
  4615. });
  4616. if (res.ok) {
  4617. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  4618. closePPPSecretModal();
  4619. loadPPPSecrets();
  4620. } else {
  4621. const err = await res.json();
  4622. showToast('Error', err.message, 'error');
  4623. }
  4624. } catch (err) {
  4625. showToast('Error', err.message, 'error');
  4626. }
  4627. }
  4628. async function togglePPPSecretState(id, disabled) {
  4629. try {
  4630. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  4631. method: 'POST',
  4632. headers: { 'Content-Type': 'application/json' },
  4633. body: JSON.stringify({ disabled })
  4634. });
  4635. if (res.ok) {
  4636. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  4637. loadPPPSecrets();
  4638. }
  4639. } catch (err) {
  4640. showToast('Error', err.message, 'error');
  4641. }
  4642. }
  4643. async function deletePPPSecret(id) {
  4644. if (!confirm('Are you sure you want to delete this secret account?')) return;
  4645. try {
  4646. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4647. if (res.ok) {
  4648. showToast('Deleted', 'Secret account removed', 'success');
  4649. loadPPPSecrets();
  4650. }
  4651. } catch (err) {
  4652. showToast('Error', err.message, 'error');
  4653. }
  4654. }
  4655. // PPP Profile Modal handlers
  4656. function openAddPPPProfileModal() {
  4657. document.getElementById('profile-modal-name').value = '';
  4658. document.getElementById('profile-modal-local').value = '10.10.10.1';
  4659. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  4660. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  4661. document.getElementById('profile-modal-encryption').value = 'required';
  4662. document.getElementById('profile-modal-onlyone').checked = true;
  4663. document.getElementById('profile-modal-comment').value = '';
  4664. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  4665. }
  4666. function closePPPProfileModal() {
  4667. document.getElementById('ppp-profile-modal').classList.add('hidden');
  4668. }
  4669. async function submitSavePPPProfile(e) {
  4670. e.preventDefault();
  4671. const name = document.getElementById('profile-modal-name').value.trim();
  4672. const local = document.getElementById('profile-modal-local').value.trim();
  4673. const remote = document.getElementById('profile-modal-remote').value.trim();
  4674. const dns = document.getElementById('profile-modal-dns').value.trim();
  4675. const enc = document.getElementById('profile-modal-encryption').value;
  4676. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  4677. const comment = document.getElementById('profile-modal-comment').value.trim();
  4678. try {
  4679. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  4680. method: 'POST',
  4681. headers: { 'Content-Type': 'application/json' },
  4682. body: JSON.stringify({
  4683. id: name,
  4684. name,
  4685. local_address: local,
  4686. remote_address: remote,
  4687. dns_servers: dns,
  4688. use_encryption: enc,
  4689. only_one: onlyone,
  4690. comment
  4691. })
  4692. });
  4693. if (res.ok) {
  4694. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  4695. closePPPProfileModal();
  4696. loadPPPProfiles();
  4697. } else {
  4698. const err = await res.json();
  4699. showToast('Error', err.message, 'error');
  4700. }
  4701. } catch (err) {
  4702. showToast('Error', err.message, 'error');
  4703. }
  4704. }
  4705. async function deletePPPProfile(name) {
  4706. if (!confirm(`Delete PPP profile ${name}?`)) return;
  4707. try {
  4708. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  4709. if (res.ok) {
  4710. showToast('Deleted', 'Profile removed', 'success');
  4711. loadPPPProfiles();
  4712. } else {
  4713. const err = await res.json();
  4714. showToast('Error', err.message, 'error');
  4715. }
  4716. } catch (err) {
  4717. showToast('Error', err.message, 'error');
  4718. }
  4719. }
  4720. // Server Config submissions
  4721. async function savePPPoEServerConfig(e) {
  4722. e.preventDefault();
  4723. const enabled = document.getElementById('pppoe-server-enabled').checked;
  4724. const name = document.getElementById('pppoe-server-name').value.trim();
  4725. const iface = document.getElementById('pppoe-server-iface').value;
  4726. const profile = document.getElementById('pppoe-server-profile').value;
  4727. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  4728. const onesession = document.getElementById('pppoe-server-onesession').checked;
  4729. try {
  4730. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  4731. method: 'POST',
  4732. headers: { 'Content-Type': 'application/json' },
  4733. body: JSON.stringify({
  4734. enabled,
  4735. service_name: name,
  4736. interface: iface,
  4737. default_profile: profile,
  4738. max_mtu: mtu,
  4739. max_mru: mtu,
  4740. one_session_per_host: onesession
  4741. })
  4742. });
  4743. if (res.ok) {
  4744. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  4745. loadPPPServers();
  4746. fetchData(false);
  4747. } else {
  4748. const err = await res.json();
  4749. showToast('Error', err.message, 'error');
  4750. }
  4751. } catch (err) {
  4752. showToast('Error', err.message, 'error');
  4753. }
  4754. }
  4755. async function savePPTPServerConfig(e) {
  4756. e.preventDefault();
  4757. const enabled = document.getElementById('pptp-server-enabled').checked;
  4758. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  4759. const profile = document.getElementById('pptp-server-profile').value;
  4760. const mppe = document.getElementById('pptp-server-mppe').checked;
  4761. try {
  4762. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  4763. method: 'POST',
  4764. headers: { 'Content-Type': 'application/json' },
  4765. body: JSON.stringify({
  4766. enabled,
  4767. port,
  4768. default_profile: profile,
  4769. require_mppe: mppe
  4770. })
  4771. });
  4772. if (res.ok) {
  4773. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  4774. loadPPPServers();
  4775. fetchData(false);
  4776. } else {
  4777. const err = await res.json();
  4778. showToast('Error', err.message, 'error');
  4779. }
  4780. } catch (err) {
  4781. showToast('Error', err.message, 'error');
  4782. }
  4783. }
  4784. async function saveL2TPServerConfig(e) {
  4785. e.preventDefault();
  4786. const enabled = document.getElementById('l2tp-server-enabled').checked;
  4787. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  4788. const profile = document.getElementById('l2tp-server-profile').value;
  4789. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  4790. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  4791. try {
  4792. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  4793. method: 'POST',
  4794. headers: { 'Content-Type': 'application/json' },
  4795. body: JSON.stringify({
  4796. enabled,
  4797. port,
  4798. default_profile: profile,
  4799. use_ipsec: useipsec,
  4800. ipsec_secret: psk
  4801. })
  4802. });
  4803. if (res.ok) {
  4804. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  4805. loadPPPServers();
  4806. fetchData(false);
  4807. } else {
  4808. const err = await res.json();
  4809. showToast('Error', err.message, 'error');
  4810. }
  4811. } catch (err) {
  4812. showToast('Error', err.message, 'error');
  4813. }
  4814. }
  4815. // IPSec Server Modal
  4816. function openIPSecServerModal() {
  4817. loadPPPServers();
  4818. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  4819. }
  4820. function closeIPSecServerModal() {
  4821. document.getElementById('ipsec-server-modal').classList.add('hidden');
  4822. }
  4823. async function submitSaveIPSecServer(e) {
  4824. e.preventDefault();
  4825. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  4826. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  4827. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  4828. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  4829. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  4830. try {
  4831. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  4832. method: 'POST',
  4833. headers: { 'Content-Type': 'application/json' },
  4834. body: JSON.stringify({
  4835. enabled,
  4836. preshared_key: psk,
  4837. pool_address: pool,
  4838. dns_servers: dns,
  4839. local_subnet: subnet
  4840. })
  4841. });
  4842. if (res.ok) {
  4843. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  4844. closeIPSecServerModal();
  4845. loadPPPServers();
  4846. fetchData(false);
  4847. } else {
  4848. const err = await res.json();
  4849. showToast('Error', err.message, 'error');
  4850. }
  4851. } catch (err) {
  4852. showToast('Error', err.message, 'error');
  4853. }
  4854. }
  4855. // WireGuard Client Config Viewer
  4856. let currentWGClientConf = '';
  4857. async function openWGClientConfModal(iface, clientIP) {
  4858. try {
  4859. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  4860. method: 'POST',
  4861. headers: { 'Content-Type': 'application/json' },
  4862. body: JSON.stringify({
  4863. interface: iface,
  4864. address: clientIP || '10.10.0.2/32',
  4865. dns: '1.1.1.1, 8.8.8.8'
  4866. })
  4867. });
  4868. if (res.ok) {
  4869. const data = await res.json();
  4870. currentWGClientConf = data.config;
  4871. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  4872. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  4873. } else {
  4874. const err = await res.json();
  4875. showToast('Error', err.message, 'error');
  4876. }
  4877. } catch (err) {
  4878. showToast('Error', err.message, 'error');
  4879. }
  4880. }
  4881. function closeWGClientConfModal() {
  4882. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  4883. }
  4884. function copyWGClientConf() {
  4885. if (!currentWGClientConf) return;
  4886. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  4887. }
  4888. function downloadWGClientConf() {
  4889. if (!currentWGClientConf) return;
  4890. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  4891. const a = document.createElement('a');
  4892. a.href = URL.createObjectURL(blob);
  4893. a.download = 'wireguard-client.conf';
  4894. document.body.appendChild(a);
  4895. a.click();
  4896. document.body.removeChild(a);
  4897. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  4898. }
  4899. // =========================================================================
  4900. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  4901. // =========================================================================
  4902. state.activeDynSubTab = 'bgp-peers';
  4903. state.activeBgpSubTab = 'bgp-peers';
  4904. state.activeOspfSubTab = 'ospf-ifaces';
  4905. state.bgpInstance = null;
  4906. state.bgpPeers = [];
  4907. state.bgpNets = [];
  4908. state.bgpRoutes = [];
  4909. state.ospfInstance = null;
  4910. state.ospfInterfaces = [];
  4911. state.ospfAreas = [];
  4912. state.ospfNeighbors = [];
  4913. state.ospfRoutes = [];
  4914. function switchBgpSubTab(subTab) {
  4915. state.activeBgpSubTab = subTab;
  4916. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes'];
  4917. tabs.forEach(t => {
  4918. const el = document.getElementById(`dyn-subtab-${t}`);
  4919. const btn = document.getElementById(`bgp-subtab-btn-${t}`);
  4920. if (el) el.classList.toggle('hidden', t !== subTab);
  4921. if (btn) {
  4922. if (t === subTab) {
  4923. 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';
  4924. } else {
  4925. 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';
  4926. }
  4927. }
  4928. });
  4929. }
  4930. function switchOspfSubTab(subTab) {
  4931. state.activeOspfSubTab = subTab;
  4932. const tabs = ['ospf-ifaces', 'ospf-areas', 'ospf-nbrs', 'ospf-routes'];
  4933. tabs.forEach(t => {
  4934. const el = document.getElementById(`dyn-subtab-${t}`);
  4935. const btn = document.getElementById(`ospf-subtab-btn-${t}`);
  4936. if (el) el.classList.toggle('hidden', t !== subTab);
  4937. if (btn) {
  4938. if (t === subTab) {
  4939. 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';
  4940. } else {
  4941. 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';
  4942. }
  4943. }
  4944. });
  4945. }
  4946. function switchDynSubTab(subTab) {
  4947. if (subTab.startsWith('bgp')) {
  4948. if (state.activeTab !== 'bgp') navigate('bgp');
  4949. switchBgpSubTab(subTab);
  4950. } else if (subTab.startsWith('ospf')) {
  4951. if (state.activeTab !== 'ospf') navigate('ospf');
  4952. switchOspfSubTab(subTab);
  4953. }
  4954. }
  4955. async function loadDynamicRouting(showToastMsg = false) {
  4956. try {
  4957. const fetchSafeJson = async (url) => {
  4958. try {
  4959. const r = await fetch(url);
  4960. return r.ok ? await r.json() : null;
  4961. } catch (e) {
  4962. return null;
  4963. }
  4964. };
  4965. const [sum, bgpInst, bgpPeers, bgpNets, bgpRoutes, ospfInst, ospfIfaces, ospfAreas, ospfNbrs, ospfRoutes, filters] = await Promise.all([
  4966. fetchSafeJson(`${API_BASE}/routing/dynamic/summary`),
  4967. fetchSafeJson(`${API_BASE}/routing/bgp/instance`),
  4968. fetchSafeJson(`${API_BASE}/routing/bgp/peers`),
  4969. fetchSafeJson(`${API_BASE}/routing/bgp/networks`),
  4970. fetchSafeJson(`${API_BASE}/routing/bgp/routes`),
  4971. fetchSafeJson(`${API_BASE}/routing/ospf/instance`),
  4972. fetchSafeJson(`${API_BASE}/routing/ospf/interfaces`),
  4973. fetchSafeJson(`${API_BASE}/routing/ospf/areas`),
  4974. fetchSafeJson(`${API_BASE}/routing/ospf/neighbors`),
  4975. fetchSafeJson(`${API_BASE}/routing/ospf/routes`),
  4976. fetchSafeJson(`${API_BASE}/routing/filters`)
  4977. ]);
  4978. if (sum) state.dynSummary = sum;
  4979. if (bgpInst) state.bgpInstance = bgpInst;
  4980. if (bgpPeers) state.bgpPeers = bgpPeers;
  4981. if (bgpNets) state.bgpNets = bgpNets;
  4982. if (bgpRoutes) state.bgpRoutes = bgpRoutes;
  4983. if (ospfInst) state.ospfInstance = ospfInst;
  4984. if (ospfIfaces) state.ospfInterfaces = ospfIfaces;
  4985. if (ospfAreas) state.ospfAreas = ospfAreas;
  4986. if (ospfNbrs) state.ospfNeighbors = ospfNbrs;
  4987. if (ospfRoutes) state.ospfRoutes = ospfRoutes;
  4988. if (filters) state.routingFilters = filters;
  4989. try { renderBgpStatusPill(); } catch(e) { console.error('renderBgpStatusPill error:', e); }
  4990. try { renderBgpPeers(); } catch(e) { console.error('renderBgpPeers error:', e); }
  4991. try { renderBgpNetworks(); } catch(e) { console.error('renderBgpNetworks error:', e); }
  4992. try { renderBgpRoutes(); } catch(e) { console.error('renderBgpRoutes error:', e); }
  4993. try { renderOspfStatusPill(); } catch(e) { console.error('renderOspfStatusPill error:', e); }
  4994. try { renderOspfInterfaces(); } catch(e) { console.error('renderOspfInterfaces error:', e); }
  4995. try { renderOspfAreas(); } catch(e) { console.error('renderOspfAreas error:', e); }
  4996. try { renderOspfNeighbors(); } catch(e) { console.error('renderOspfNeighbors error:', e); }
  4997. try { renderOspfRoutes(); } catch(e) { console.error('renderOspfRoutes error:', e); }
  4998. try { renderRoutingFilters(); } catch(e) { console.error('renderRoutingFilters error:', e); }
  4999. try { updateBadges(); } catch(e) { console.error('updateBadges error:', e); }
  5000. if (showToastMsg) showToast('Refreshed', 'Dynamic routing telemetry updated', 'info');
  5001. } catch (err) {
  5002. console.error('Failed to load dynamic routing:', err);
  5003. if (showToastMsg) showToast('Notice', 'Unable to refresh dynamic routing telemetry', 'warning');
  5004. }
  5005. }
  5006. function renderBgpStatusPill() {
  5007. const pill = document.getElementById('bgp-live-status-pill');
  5008. if (!pill) return;
  5009. const inst = state.bgpInstance;
  5010. if (!inst || !inst.enabled) {
  5011. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  5012. pill.innerText = 'BGP DISABLED';
  5013. } else if (inst.running) {
  5014. 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';
  5015. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  5016. } else {
  5017. 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';
  5018. pill.innerText = 'BGP STARTING...';
  5019. }
  5020. }
  5021. function renderBgpPeers() {
  5022. const tbody = document.getElementById('bgp-peers-table-body');
  5023. if (!tbody) return;
  5024. const empty = document.getElementById('bgp-peers-empty');
  5025. const countBadge = document.getElementById('bgp-peers-count-badge');
  5026. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  5027. const peers = state.bgpPeers || [];
  5028. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  5029. if (navBadge) navBadge.innerText = peers.length;
  5030. if (peers.length === 0) {
  5031. tbody.innerHTML = '';
  5032. if (empty) empty.classList.remove('hidden');
  5033. return;
  5034. }
  5035. if (empty) empty.classList.add('hidden');
  5036. tbody.innerHTML = peers.map(p => {
  5037. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  5038. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  5039. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  5040. let stateBadge = '';
  5041. if (p.disabled) {
  5042. 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>';
  5043. } else if (p.state === 'Established') {
  5044. 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>';
  5045. } else if (p.state === 'Connect' || p.state === 'Active') {
  5046. 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>`;
  5047. } else {
  5048. 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>`;
  5049. }
  5050. return `
  5051. <tr class="hover:bg-slate-800/40 transition">
  5052. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  5053. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  5054. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  5055. <td class="py-2.5 px-3 font-bold text-slate-200">AS ${p.remote_as}</td>
  5056. <td class="py-2.5 px-3">${stateBadge}</td>
  5057. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  5058. <td class="py-2.5 px-3 text-slate-300">
  5059. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  5060. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  5061. </td>
  5062. <td class="py-2.5 px-3 font-mono text-[11px] whitespace-nowrap">
  5063. ${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> ` : ''}
  5064. ${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>` : ''}
  5065. ${!p.in_filter && !p.out_filter ? '<span class="text-slate-600">-</span>' : ''}
  5066. </td>
  5067. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  5068. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  5069. <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'}">
  5070. ${p.disabled ? 'Enable' : 'Disable'}
  5071. </button>
  5072. <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">
  5073. Edit
  5074. </button>
  5075. <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">
  5076. Delete
  5077. </button>
  5078. </td>
  5079. </tr>
  5080. `;
  5081. }).join('');
  5082. }
  5083. function renderBgpNetworks() {
  5084. const tbody = document.getElementById('bgp-nets-table-body');
  5085. if (!tbody) return;
  5086. const empty = document.getElementById('bgp-nets-empty');
  5087. const countBadge = document.getElementById('bgp-nets-count-badge');
  5088. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  5089. const nets = state.bgpNets || [];
  5090. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  5091. if (navBadge) navBadge.innerText = nets.length;
  5092. if (nets.length === 0) {
  5093. tbody.innerHTML = '';
  5094. if (empty) empty.classList.remove('hidden');
  5095. return;
  5096. }
  5097. if (empty) empty.classList.add('hidden');
  5098. tbody.innerHTML = nets.map(n => `
  5099. <tr class="hover:bg-slate-800/40 transition">
  5100. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  5101. <td class="py-2.5 px-3">
  5102. ${n.disabled
  5103. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  5104. : '<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>'}
  5105. </td>
  5106. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  5107. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  5108. <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">
  5109. Delete
  5110. </button>
  5111. </td>
  5112. </tr>
  5113. `).join('');
  5114. }
  5115. function renderBgpRoutes() {
  5116. const tbody = document.getElementById('bgp-routes-table-body');
  5117. if (!tbody) return;
  5118. const empty = document.getElementById('bgp-routes-empty');
  5119. const countBadge = document.getElementById('bgp-routes-count-badge');
  5120. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  5121. const routes = state.bgpRoutes || [];
  5122. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  5123. if (navBadge) navBadge.innerText = routes.length;
  5124. if (routes.length === 0) {
  5125. tbody.innerHTML = '';
  5126. if (empty) empty.classList.remove('hidden');
  5127. return;
  5128. }
  5129. if (empty) empty.classList.add('hidden');
  5130. tbody.innerHTML = routes.map(r => `
  5131. <tr class="hover:bg-slate-800/40 transition">
  5132. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  5133. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  5134. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  5135. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  5136. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  5137. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  5138. </tr>
  5139. `).join('');
  5140. }
  5141. function renderOspfStatusPill() {
  5142. const pill = document.getElementById('ospf-live-status-pill');
  5143. if (!pill) return;
  5144. const inst = state.ospfInstance;
  5145. if (!inst || !inst.enabled) {
  5146. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  5147. pill.innerText = 'OSPF DISABLED';
  5148. } else if (inst.running) {
  5149. 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';
  5150. pill.innerText = `OSPF ACTIVE (ID: ${inst.router_id || 'Auto'})`;
  5151. } else {
  5152. 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';
  5153. pill.innerText = 'OSPF STARTING...';
  5154. }
  5155. }
  5156. function renderOspfInterfaces() {
  5157. const tbody = document.getElementById('ospf-ifaces-table-body');
  5158. if (!tbody) return;
  5159. const empty = document.getElementById('ospf-ifaces-empty');
  5160. const countBadge = document.getElementById('ospf-ifaces-count-badge');
  5161. const navBadge = document.getElementById('dyn-badge-ospf-ifaces');
  5162. const ifaces = state.ospfInterfaces || [];
  5163. if (countBadge) countBadge.innerText = `${ifaces.length} Interfaces`;
  5164. if (navBadge) navBadge.innerText = ifaces.length;
  5165. if (ifaces.length === 0) {
  5166. tbody.innerHTML = '';
  5167. if (empty) empty.classList.remove('hidden');
  5168. return;
  5169. }
  5170. if (empty) empty.classList.add('hidden');
  5171. tbody.innerHTML = ifaces.map(i => {
  5172. let flagA = !i.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  5173. let flagP = i.passive ? '<span class="text-amber-400 font-bold ml-1" title="Passive">P</span>' : '';
  5174. let flagX = i.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  5175. return `
  5176. <tr class="hover:bg-slate-800/40 transition">
  5177. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagP}${flagX}</td>
  5178. <td class="py-2.5 px-3 font-semibold text-white font-mono">${escapeHtml(i.network)}</td>
  5179. <td class="py-2.5 px-3 text-indigo-300 font-bold">Area ${escapeHtml(i.area)}</td>
  5180. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(i.interface || 'Any')}</td>
  5181. <td class="py-2.5 px-3 text-slate-300">${i.cost}</td>
  5182. <td class="py-2.5 px-3 text-slate-300">${i.priority}</td>
  5183. <td class="py-2.5 px-3 text-slate-400">${i.hello_interval}s / ${i.dead_interval}s</td>
  5184. <td class="py-2.5 px-3 text-slate-300 uppercase">${escapeHtml(i.auth_type || 'none')}</td>
  5185. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(i.comment || '')}</td>
  5186. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  5187. <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'}">
  5188. ${i.disabled ? 'Enable' : 'Disable'}
  5189. </button>
  5190. <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">
  5191. Edit
  5192. </button>
  5193. <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">
  5194. Delete
  5195. </button>
  5196. </td>
  5197. </tr>
  5198. `;
  5199. }).join('');
  5200. }
  5201. function renderOspfAreas() {
  5202. const tbody = document.getElementById('ospf-areas-table-body');
  5203. if (!tbody) return;
  5204. const countBadge = document.getElementById('ospf-areas-count-badge');
  5205. const navBadge = document.getElementById('dyn-badge-ospf-areas');
  5206. const areas = state.ospfAreas || [];
  5207. if (countBadge) countBadge.innerText = `${areas.length} Areas`;
  5208. if (navBadge) navBadge.innerText = areas.length;
  5209. tbody.innerHTML = areas.map(a => `
  5210. <tr class="hover:bg-slate-800/40 transition">
  5211. <td class="py-2.5 px-3 font-semibold text-white font-mono">${escapeHtml(a.name)}</td>
  5212. <td class="py-2.5 px-3 font-bold text-indigo-300">${escapeHtml(a.area_id)}</td>
  5213. <td class="py-2.5 px-3 text-slate-300 uppercase">${escapeHtml(a.area_type || 'default')}</td>
  5214. <td class="py-2.5 px-3 text-slate-400 font-sans">${escapeHtml(a.comment || '')}</td>
  5215. <td class="py-2.5 px-3 text-right font-sans">
  5216. <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">
  5217. Delete
  5218. </button>
  5219. </td>
  5220. </tr>
  5221. `).join('');
  5222. }
  5223. function renderOspfNeighbors() {
  5224. const tbody = document.getElementById('ospf-nbrs-table-body');
  5225. if (!tbody) return;
  5226. const empty = document.getElementById('ospf-nbrs-empty');
  5227. const countBadge = document.getElementById('ospf-nbrs-count-badge');
  5228. const navBadge = document.getElementById('dyn-badge-ospf-nbrs');
  5229. const nbrs = state.ospfNeighbors || [];
  5230. if (countBadge) countBadge.innerText = `${nbrs.length} Neighbors`;
  5231. if (navBadge) navBadge.innerText = nbrs.length;
  5232. if (nbrs.length === 0) {
  5233. tbody.innerHTML = '';
  5234. if (empty) empty.classList.remove('hidden');
  5235. return;
  5236. }
  5237. if (empty) empty.classList.add('hidden');
  5238. tbody.innerHTML = nbrs.map(n => {
  5239. let stateBadge = '';
  5240. if (n.state && (n.state.startsWith('Full') || n.state.includes('DR') || n.state.includes('Backup'))) {
  5241. 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>`;
  5242. } else {
  5243. 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>`;
  5244. }
  5245. return `
  5246. <tr class="hover:bg-slate-800/40 transition">
  5247. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(n.neighbor_id)}</td>
  5248. <td class="py-2.5 px-3 text-indigo-300 font-bold">${escapeHtml(n.address)}</td>
  5249. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(n.interface)}</td>
  5250. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(n.area || '0.0.0.0')}</td>
  5251. <td class="py-2.5 px-3">${stateBadge}</td>
  5252. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(n.dead_timer || '-')}</td>
  5253. </tr>
  5254. `;
  5255. }).join('');
  5256. }
  5257. function renderOspfRoutes() {
  5258. const tbody = document.getElementById('ospf-routes-table-body');
  5259. if (!tbody) return;
  5260. const empty = document.getElementById('ospf-routes-empty');
  5261. const countBadge = document.getElementById('ospf-routes-count-badge');
  5262. const navBadge = document.getElementById('dyn-badge-ospf-routes');
  5263. const routes = state.ospfRoutes || [];
  5264. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  5265. if (navBadge) navBadge.innerText = routes.length;
  5266. if (routes.length === 0) {
  5267. tbody.innerHTML = '';
  5268. if (empty) empty.classList.remove('hidden');
  5269. return;
  5270. }
  5271. if (empty) empty.classList.add('hidden');
  5272. tbody.innerHTML = routes.map(r => `
  5273. <tr class="hover:bg-slate-800/40 transition">
  5274. <td class="py-2.5 px-3 font-semibold text-white font-mono">${escapeHtml(r.prefix)}</td>
  5275. <td class="py-2.5 px-3 text-slate-300">${escapeHtml(r.route_type || 'Network')}</td>
  5276. <td class="py-2.5 px-3 text-slate-300">${r.cost}</td>
  5277. <td class="py-2.5 px-3 text-indigo-300 font-bold">Area ${escapeHtml(r.area || '0.0.0.0')}</td>
  5278. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(r.next_hop || r.interface || '-')}</td>
  5279. </tr>
  5280. `).join('');
  5281. }
  5282. // BGP Modals & Actions
  5283. function openBgpInstanceModal() {
  5284. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  5285. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  5286. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  5287. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  5288. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  5289. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  5290. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  5291. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  5292. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  5293. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  5294. }
  5295. function closeBgpInstanceModal() {
  5296. document.getElementById('bgp-instance-modal').classList.add('hidden');
  5297. }
  5298. async function submitBgpInstance(e) {
  5299. e.preventDefault();
  5300. const payload = {
  5301. enabled: document.getElementById('modal-bgp-enabled').checked,
  5302. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  5303. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  5304. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  5305. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  5306. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  5307. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  5308. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  5309. };
  5310. try {
  5311. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  5312. method: 'POST',
  5313. headers: { 'Content-Type': 'application/json' },
  5314. body: JSON.stringify(payload)
  5315. });
  5316. if (res.ok) {
  5317. closeBgpInstanceModal();
  5318. showToast('Success', 'BGP instance configuration updated', 'success');
  5319. loadDynamicRouting();
  5320. } else {
  5321. const err = await res.json();
  5322. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  5323. }
  5324. } catch (err) {
  5325. showToast('Error', err.message, 'error');
  5326. }
  5327. }
  5328. function openAddBgpPeerModal() {
  5329. document.getElementById('bgp-peer-form').reset();
  5330. document.getElementById('modal-bgp-peer-id').value = '';
  5331. document.getElementById('bgp-peer-modal-title').innerText = 'Add BGP Peer Connection';
  5332. document.getElementById('modal-bgp-peer-nexthop-self').checked = true;
  5333. const inFilterEl = document.getElementById('modal-bgp-peer-in-filter');
  5334. if (inFilterEl) inFilterEl.value = '';
  5335. const outFilterEl = document.getElementById('modal-bgp-peer-out-filter');
  5336. if (outFilterEl) outFilterEl.value = '';
  5337. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  5338. }
  5339. function openEditBgpPeerModal(id) {
  5340. const p = (state.bgpPeers || []).find(item => item.id === id);
  5341. if (!p) return;
  5342. document.getElementById('modal-bgp-peer-id').value = p.id;
  5343. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  5344. document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  5345. document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  5346. document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  5347. document.getElementById('modal-bgp-peer-password').value = p.password || '';
  5348. document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  5349. document.getElementById('modal-bgp-peer-nexthop-self').checked = !!p.nexthop_self;
  5350. document.getElementById('modal-bgp-peer-passive').checked = !!p.passive;
  5351. document.getElementById('modal-bgp-peer-disabled').checked = !!p.disabled;
  5352. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  5353. const inFilterEl = document.getElementById('modal-bgp-peer-in-filter');
  5354. if (inFilterEl) inFilterEl.value = p.in_filter || '';
  5355. const outFilterEl = document.getElementById('modal-bgp-peer-out-filter');
  5356. if (outFilterEl) outFilterEl.value = p.out_filter || '';
  5357. document.getElementById('bgp-peer-modal-title').innerText = 'Edit BGP Peer Connection';
  5358. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  5359. }
  5360. function closeBgpPeerModal() {
  5361. document.getElementById('bgp-peer-modal').classList.add('hidden');
  5362. }
  5363. async function submitBgpPeer(e) {
  5364. e.preventDefault();
  5365. const payload = {
  5366. id: document.getElementById('modal-bgp-peer-id').value,
  5367. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  5368. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  5369. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10),
  5370. local_address: document.getElementById('modal-bgp-peer-local-addr').value.trim(),
  5371. password: document.getElementById('modal-bgp-peer-password').value,
  5372. multihop: document.getElementById('modal-bgp-peer-multihop').checked,
  5373. nexthop_self: document.getElementById('modal-bgp-peer-nexthop-self').checked,
  5374. passive: document.getElementById('modal-bgp-peer-passive').checked,
  5375. disabled: document.getElementById('modal-bgp-peer-disabled').checked,
  5376. in_filter: (document.getElementById('modal-bgp-peer-in-filter')?.value || '').trim(),
  5377. out_filter: (document.getElementById('modal-bgp-peer-out-filter')?.value || '').trim(),
  5378. comment: document.getElementById('modal-bgp-peer-comment').value.trim()
  5379. };
  5380. try {
  5381. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  5382. method: 'POST',
  5383. headers: { 'Content-Type': 'application/json' },
  5384. body: JSON.stringify(payload)
  5385. });
  5386. if (res.ok) {
  5387. closeBgpPeerModal();
  5388. showToast('Success', 'BGP Peer saved', 'success');
  5389. loadDynamicRouting();
  5390. } else {
  5391. const err = await res.json();
  5392. showToast('Error', err.error || 'Failed to save peer', 'error');
  5393. }
  5394. } catch (err) {
  5395. showToast('Error', err.message, 'error');
  5396. }
  5397. }
  5398. async function deleteBgpPeer(id) {
  5399. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  5400. try {
  5401. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5402. if (res.ok) {
  5403. showToast('Deleted', 'BGP peer removed', 'success');
  5404. loadDynamicRouting();
  5405. }
  5406. } catch (err) {
  5407. showToast('Error', err.message, 'error');
  5408. }
  5409. }
  5410. async function toggleBgpPeerState(id, disabled) {
  5411. try {
  5412. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  5413. method: 'POST',
  5414. headers: { 'Content-Type': 'application/json' },
  5415. body: JSON.stringify({ disabled })
  5416. });
  5417. if (res.ok) {
  5418. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  5419. loadDynamicRouting();
  5420. }
  5421. } catch (err) {
  5422. showToast('Error', err.message, 'error');
  5423. }
  5424. }
  5425. function openAddBgpNetworkModal() {
  5426. document.getElementById('bgp-network-form').reset();
  5427. document.getElementById('modal-bgp-net-id').value = '';
  5428. document.getElementById('bgp-network-modal').classList.remove('hidden');
  5429. }
  5430. function closeBgpNetworkModal() {
  5431. document.getElementById('bgp-network-modal').classList.add('hidden');
  5432. }
  5433. async function submitBgpNetwork(e) {
  5434. e.preventDefault();
  5435. const payload = {
  5436. id: document.getElementById('modal-bgp-net-id').value,
  5437. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  5438. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  5439. disabled: document.getElementById('modal-bgp-net-disabled').checked
  5440. };
  5441. try {
  5442. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  5443. method: 'POST',
  5444. headers: { 'Content-Type': 'application/json' },
  5445. body: JSON.stringify(payload)
  5446. });
  5447. if (res.ok) {
  5448. closeBgpNetworkModal();
  5449. showToast('Success', 'BGP network advertisement saved', 'success');
  5450. loadDynamicRouting();
  5451. } else {
  5452. const err = await res.json();
  5453. showToast('Error', err.error || 'Failed to save network', 'error');
  5454. }
  5455. } catch (err) {
  5456. showToast('Error', err.message, 'error');
  5457. }
  5458. }
  5459. async function deleteBgpNetwork(id) {
  5460. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  5461. try {
  5462. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5463. if (res.ok) {
  5464. showToast('Deleted', 'Network advertisement removed', 'success');
  5465. loadDynamicRouting();
  5466. }
  5467. } catch (err) {
  5468. showToast('Error', err.message, 'error');
  5469. }
  5470. }
  5471. // OSPF Modals & Actions
  5472. function openOspfInstanceModal() {
  5473. const inst = state.ospfInstance || { enabled: false, router_id: '192.168.131.56', default_metric: 10 };
  5474. document.getElementById('modal-ospf-enabled').checked = !!inst.enabled;
  5475. document.getElementById('modal-ospf-router-id').value = inst.router_id || '';
  5476. document.getElementById('modal-ospf-metric').value = inst.default_metric || 10;
  5477. document.getElementById('modal-ospf-redist-conn').checked = !!inst.redistribute_connected;
  5478. document.getElementById('modal-ospf-redist-static').checked = !!inst.redistribute_static;
  5479. document.getElementById('modal-ospf-redist-bgp').checked = !!inst.redistribute_bgp;
  5480. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  5481. }
  5482. function closeOspfInstanceModal() {
  5483. document.getElementById('ospf-instance-modal').classList.add('hidden');
  5484. }
  5485. async function submitOspfInstance(e) {
  5486. e.preventDefault();
  5487. const payload = {
  5488. enabled: document.getElementById('modal-ospf-enabled').checked,
  5489. router_id: document.getElementById('modal-ospf-router-id').value.trim(),
  5490. default_metric: parseInt(document.getElementById('modal-ospf-metric').value, 10),
  5491. redistribute_connected: document.getElementById('modal-ospf-redist-conn').checked,
  5492. redistribute_static: document.getElementById('modal-ospf-redist-static').checked,
  5493. redistribute_bgp: document.getElementById('modal-ospf-redist-bgp').checked
  5494. };
  5495. try {
  5496. const res = await fetch(`${API_BASE}/routing/ospf/instance`, {
  5497. method: 'POST',
  5498. headers: { 'Content-Type': 'application/json' },
  5499. body: JSON.stringify(payload)
  5500. });
  5501. if (res.ok) {
  5502. closeOspfInstanceModal();
  5503. showToast('Success', 'OSPF instance configuration updated', 'success');
  5504. loadDynamicRouting();
  5505. } else {
  5506. const err = await res.json();
  5507. showToast('Error', err.error || 'Failed to update OSPF instance', 'error');
  5508. }
  5509. } catch (err) {
  5510. showToast('Error', err.message, 'error');
  5511. }
  5512. }
  5513. function openAddOspfAreaModal() {
  5514. document.getElementById('ospf-area-form').reset();
  5515. document.getElementById('modal-ospf-area-id').value = '';
  5516. document.getElementById('modal-ospf-area-areaid').value = '0.0.0.0';
  5517. document.getElementById('ospf-area-modal').classList.remove('hidden');
  5518. }
  5519. function closeOspfAreaModal() {
  5520. document.getElementById('ospf-area-modal').classList.add('hidden');
  5521. }
  5522. async function submitOspfArea(e) {
  5523. e.preventDefault();
  5524. const payload = {
  5525. id: document.getElementById('modal-ospf-area-id').value,
  5526. name: document.getElementById('modal-ospf-area-name').value.trim(),
  5527. area_id: document.getElementById('modal-ospf-area-areaid').value.trim(),
  5528. area_type: document.getElementById('modal-ospf-area-type').value,
  5529. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  5530. };
  5531. try {
  5532. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  5533. method: 'POST',
  5534. headers: { 'Content-Type': 'application/json' },
  5535. body: JSON.stringify(payload)
  5536. });
  5537. if (res.ok) {
  5538. closeOspfAreaModal();
  5539. showToast('Success', 'OSPF area saved', 'success');
  5540. loadDynamicRouting();
  5541. } else {
  5542. const err = await res.json();
  5543. showToast('Error', err.error || 'Failed to save area', 'error');
  5544. }
  5545. } catch (err) {
  5546. showToast('Error', err.message, 'error');
  5547. }
  5548. }
  5549. async function deleteOspfArea(id) {
  5550. if (!confirm('Are you sure you want to delete this OSPF area?')) return;
  5551. try {
  5552. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5553. if (res.ok) {
  5554. showToast('Deleted', 'OSPF area removed', 'success');
  5555. loadDynamicRouting();
  5556. }
  5557. } catch (err) {
  5558. showToast('Error', err.message, 'error');
  5559. }
  5560. }
  5561. function populateOspfInterfaceDevices() {
  5562. const select = document.getElementById('modal-ospf-iface-device');
  5563. if (!select) return;
  5564. const current = select.value;
  5565. select.innerHTML = '<option value="">Any matching interface</option>';
  5566. (state.interfaces || []).forEach(iface => {
  5567. select.innerHTML += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)} (${iface.type})</option>`;
  5568. });
  5569. if (current) select.value = current;
  5570. }
  5571. function openAddOspfInterfaceModal() {
  5572. document.getElementById('ospf-interface-form').reset();
  5573. document.getElementById('modal-ospf-iface-id').value = '';
  5574. document.getElementById('modal-ospf-iface-area').value = '0.0.0.0';
  5575. document.getElementById('modal-ospf-iface-cost').value = '10';
  5576. document.getElementById('modal-ospf-iface-priority').value = '1';
  5577. document.getElementById('modal-ospf-iface-hello').value = '10';
  5578. document.getElementById('modal-ospf-iface-dead').value = '40';
  5579. document.getElementById('ospf-interface-modal-title').innerText = 'Add OSPF Interface';
  5580. populateOspfInterfaceDevices();
  5581. document.getElementById('ospf-interface-modal').classList.remove('hidden');
  5582. }
  5583. function openEditOspfInterfaceModal(id) {
  5584. const item = (state.ospfInterfaces || []).find(i => i.id === id);
  5585. if (!item) return;
  5586. populateOspfInterfaceDevices();
  5587. document.getElementById('modal-ospf-iface-id').value = item.id;
  5588. document.getElementById('modal-ospf-iface-net').value = item.network || '';
  5589. document.getElementById('modal-ospf-iface-area').value = item.area || '0.0.0.0';
  5590. document.getElementById('modal-ospf-iface-device').value = item.interface || '';
  5591. document.getElementById('modal-ospf-iface-cost').value = item.cost || 10;
  5592. document.getElementById('modal-ospf-iface-priority').value = item.priority || 1;
  5593. document.getElementById('modal-ospf-iface-hello').value = item.hello_interval || 10;
  5594. document.getElementById('modal-ospf-iface-dead').value = item.dead_interval || 40;
  5595. document.getElementById('modal-ospf-iface-auth-type').value = item.auth_type || 'none';
  5596. document.getElementById('modal-ospf-iface-auth-key').value = item.auth_key || '';
  5597. document.getElementById('modal-ospf-iface-passive').checked = !!item.passive;
  5598. document.getElementById('modal-ospf-iface-disabled').checked = !!item.disabled;
  5599. document.getElementById('modal-ospf-iface-comment').value = item.comment || '';
  5600. document.getElementById('ospf-interface-modal-title').innerText = 'Edit OSPF Interface';
  5601. document.getElementById('ospf-interface-modal').classList.remove('hidden');
  5602. }
  5603. function closeOspfInterfaceModal() {
  5604. document.getElementById('ospf-interface-modal').classList.add('hidden');
  5605. }
  5606. async function submitOspfInterface(e) {
  5607. e.preventDefault();
  5608. const payload = {
  5609. id: document.getElementById('modal-ospf-iface-id').value,
  5610. network: document.getElementById('modal-ospf-iface-net').value.trim(),
  5611. area: document.getElementById('modal-ospf-iface-area').value.trim(),
  5612. interface: document.getElementById('modal-ospf-iface-device').value,
  5613. cost: parseInt(document.getElementById('modal-ospf-iface-cost').value, 10),
  5614. priority: parseInt(document.getElementById('modal-ospf-iface-priority').value, 10),
  5615. hello_interval: parseInt(document.getElementById('modal-ospf-iface-hello').value, 10),
  5616. dead_interval: parseInt(document.getElementById('modal-ospf-iface-dead').value, 10),
  5617. auth_type: document.getElementById('modal-ospf-iface-auth-type').value,
  5618. auth_key: document.getElementById('modal-ospf-iface-auth-key').value,
  5619. passive: document.getElementById('modal-ospf-iface-passive').checked,
  5620. disabled: document.getElementById('modal-ospf-iface-disabled').checked,
  5621. comment: document.getElementById('modal-ospf-iface-comment').value.trim()
  5622. };
  5623. try {
  5624. const res = await fetch(`${API_BASE}/routing/ospf/interfaces`, {
  5625. method: 'POST',
  5626. headers: { 'Content-Type': 'application/json' },
  5627. body: JSON.stringify(payload)
  5628. });
  5629. if (res.ok) {
  5630. closeOspfInterfaceModal();
  5631. showToast('Success', 'OSPF interface template saved', 'success');
  5632. loadDynamicRouting();
  5633. } else {
  5634. const err = await res.json();
  5635. showToast('Error', err.error || 'Failed to save interface', 'error');
  5636. }
  5637. } catch (err) {
  5638. showToast('Error', err.message, 'error');
  5639. }
  5640. }
  5641. async function deleteOspfInterface(id) {
  5642. if (!confirm('Are you sure you want to delete this OSPF interface?')) return;
  5643. try {
  5644. const res = await fetch(`${API_BASE}/routing/ospf/interfaces/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5645. if (res.ok) {
  5646. showToast('Deleted', 'OSPF interface removed', 'success');
  5647. loadDynamicRouting();
  5648. }
  5649. } catch (err) {
  5650. showToast('Error', err.message, 'error');
  5651. }
  5652. }
  5653. async function toggleOspfInterfaceState(id, disabled) {
  5654. try {
  5655. const res = await fetch(`${API_BASE}/routing/ospf/interfaces/${encodeURIComponent(id)}/state`, {
  5656. method: 'POST',
  5657. headers: { 'Content-Type': 'application/json' },
  5658. body: JSON.stringify({ disabled })
  5659. });
  5660. if (res.ok) {
  5661. showToast('Updated', `Interface ${disabled ? 'disabled' : 'enabled'}`, 'success');
  5662. loadDynamicRouting();
  5663. }
  5664. } catch (err) {
  5665. showToast('Error', err.message, 'error');
  5666. }
  5667. }
  5668. // ============================================================================
  5669. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  5670. // ============================================================================
  5671. function switchBridgeSubTab(tab) {
  5672. state.bridgeSubTab = tab;
  5673. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  5674. tabs.forEach(t => {
  5675. const panel = document.getElementById(`bridge-subtab-${t}`);
  5676. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  5677. if (panel) {
  5678. if (t === tab) panel.classList.remove('hidden');
  5679. else panel.classList.add('hidden');
  5680. }
  5681. if (btn) {
  5682. if (t === tab) {
  5683. 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';
  5684. } else {
  5685. 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';
  5686. }
  5687. }
  5688. });
  5689. const addBtn = document.getElementById('bridge-top-action-btn');
  5690. if (addBtn) {
  5691. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  5692. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  5693. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  5694. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  5695. }
  5696. if (tab === 'hosts') loadBridgeHosts();
  5697. }
  5698. function openCurrentBridgeModal() {
  5699. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  5700. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  5701. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  5702. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  5703. }
  5704. async function loadBridge() {
  5705. try {
  5706. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vlanIfacesRes] = await Promise.all([
  5707. fetch(`${API_BASE}/bridge/bridges`),
  5708. fetch(`${API_BASE}/bridge/ports`),
  5709. fetch(`${API_BASE}/bridge/vlans`),
  5710. fetch(`${API_BASE}/bridge/summary`),
  5711. fetch(`${API_BASE}/vpn/eoip`),
  5712. fetch(`${API_BASE}/vlans`)
  5713. ]);
  5714. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  5715. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  5716. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  5717. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  5718. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  5719. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  5720. // Badges & Stats
  5721. const bBridges = document.getElementById('bridge-badge-bridges');
  5722. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  5723. const bPorts = document.getElementById('bridge-badge-ports');
  5724. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  5725. const bVlans = document.getElementById('bridge-badge-vlans');
  5726. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  5727. const bHosts = document.getElementById('bridge-badge-hosts');
  5728. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  5729. const sBr = document.getElementById('bridge-stat-bridges');
  5730. if (sBr) sBr.innerText = (state.bridges || []).length;
  5731. const sPorts = document.getElementById('bridge-stat-ports');
  5732. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  5733. const sHosts = document.getElementById('bridge-stat-hosts');
  5734. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  5735. renderBridges();
  5736. renderBridgePorts();
  5737. renderBridgeVLANs();
  5738. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  5739. } catch (err) {
  5740. console.error('Failed to load bridge subsystem:', err);
  5741. }
  5742. }
  5743. // ----------------- Bridges -----------------
  5744. function renderBridges() {
  5745. const tbody = document.getElementById('bridge-table-body');
  5746. const empty = document.getElementById('bridge-empty-bridges');
  5747. const countBadge = document.getElementById('bridge-count-badge');
  5748. if (!tbody) return;
  5749. tbody.innerHTML = '';
  5750. const bridges = state.bridges || [];
  5751. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  5752. if (bridges.length === 0) {
  5753. empty?.classList.remove('hidden');
  5754. return;
  5755. }
  5756. empty?.classList.add('hidden');
  5757. bridges.forEach((b, idx) => {
  5758. const tr = document.createElement('tr');
  5759. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  5760. // Format IP addresses pill list
  5761. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  5762. if (b.ip_addresses && b.ip_addresses.length > 0) {
  5763. ipsHtml = b.ip_addresses.map(ip => `
  5764. <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">
  5765. <span>${ip}</span>
  5766. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  5767. </span>
  5768. `).join(' ');
  5769. }
  5770. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  5771. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  5772. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  5773. tr.innerHTML = `
  5774. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  5775. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  5776. <td class="py-2.5 px-3 font-bold text-white text-sm">
  5777. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  5778. </td>
  5779. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  5780. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  5781. <td class="py-2.5 px-3">
  5782. <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>
  5783. </td>
  5784. <td class="py-2.5 px-3 text-center">
  5785. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  5786. </td>
  5787. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  5788. <td class="py-2.5 px-3">
  5789. <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>
  5790. </td>
  5791. <td class="py-2.5 px-3">
  5792. <div class="flex items-center gap-1.5 flex-wrap">
  5793. ${ipsHtml}
  5794. <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>
  5795. </div>
  5796. </td>
  5797. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  5798. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  5799. </td>
  5800. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  5801. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  5802. <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>
  5803. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  5804. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5805. </td>
  5806. `;
  5807. tbody.appendChild(tr);
  5808. });
  5809. }
  5810. function openAddBridgeModal() {
  5811. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  5812. document.getElementById('bridge-modal-id').value = '';
  5813. document.getElementById('bridge-modal-name').value = 'bridge1';
  5814. document.getElementById('bridge-modal-name').disabled = false;
  5815. document.getElementById('bridge-modal-mtu').value = '1500';
  5816. document.getElementById('bridge-modal-mac').value = '';
  5817. document.getElementById('bridge-modal-stp').value = 'rstp';
  5818. document.getElementById('bridge-modal-priority').value = '32768';
  5819. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  5820. document.getElementById('bridge-modal-pvid').value = '1';
  5821. document.getElementById('bridge-modal-fastforward').checked = true;
  5822. document.getElementById('bridge-modal-comment').value = '';
  5823. document.getElementById('bridge-modal-disabled').checked = false;
  5824. toggleBridgeModalVlanFiltering();
  5825. document.getElementById('bridge-modal').classList.remove('hidden');
  5826. }
  5827. function openEditBridgeModal(id) {
  5828. const b = (state.bridges || []).find(x => x.id === id);
  5829. if (!b) return;
  5830. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  5831. document.getElementById('bridge-modal-id').value = b.id;
  5832. document.getElementById('bridge-modal-name').value = b.name;
  5833. document.getElementById('bridge-modal-name').disabled = true;
  5834. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  5835. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  5836. document.getElementById('bridge-modal-stp').value = b.stp || 'rstp';
  5837. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  5838. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  5839. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  5840. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  5841. document.getElementById('bridge-modal-comment').value = b.comment || '';
  5842. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  5843. toggleBridgeModalVlanFiltering();
  5844. document.getElementById('bridge-modal').classList.remove('hidden');
  5845. }
  5846. function closeBridgeModal() {
  5847. document.getElementById('bridge-modal').classList.add('hidden');
  5848. }
  5849. function toggleBridgeModalVlanFiltering() {
  5850. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  5851. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  5852. if (pvidBox) {
  5853. if (chk) pvidBox.classList.remove('opacity-40');
  5854. else pvidBox.classList.add('opacity-40');
  5855. }
  5856. }
  5857. async function submitSaveBridge(e) {
  5858. e.preventDefault();
  5859. const id = document.getElementById('bridge-modal-id').value;
  5860. const name = document.getElementById('bridge-modal-name').value.trim();
  5861. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  5862. const mac = document.getElementById('bridge-modal-mac').value.trim();
  5863. const stp = document.getElementById('bridge-modal-stp').value;
  5864. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  5865. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  5866. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  5867. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  5868. const comment = document.getElementById('bridge-modal-comment').value.trim();
  5869. const disabled = document.getElementById('bridge-modal-disabled').checked;
  5870. try {
  5871. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  5872. method: 'POST',
  5873. headers: { 'Content-Type': 'application/json' },
  5874. body: JSON.stringify({
  5875. id,
  5876. name,
  5877. mtu,
  5878. mac_address: mac,
  5879. stp,
  5880. priority,
  5881. vlan_filtering: vlanFiltering,
  5882. pvid,
  5883. fast_forward: fastForward,
  5884. comment,
  5885. disabled
  5886. })
  5887. });
  5888. if (res.ok) {
  5889. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  5890. closeBridgeModal();
  5891. loadBridge();
  5892. fetchData(false);
  5893. } else {
  5894. const err = await res.json();
  5895. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  5896. }
  5897. } catch (err) {
  5898. showToast('Error', err.message, 'error');
  5899. }
  5900. }
  5901. async function toggleBridgeState(id, disabled) {
  5902. try {
  5903. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  5904. method: 'POST',
  5905. headers: { 'Content-Type': 'application/json' },
  5906. body: JSON.stringify({ disabled })
  5907. });
  5908. if (res.ok) {
  5909. loadBridge();
  5910. fetchData(false);
  5911. }
  5912. } catch (err) {
  5913. showToast('Error', err.message, 'error');
  5914. }
  5915. }
  5916. async function deleteBridge(id) {
  5917. const b = (state.bridges || []).find(x => x.id === id);
  5918. const name = b ? b.name : id;
  5919. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  5920. try {
  5921. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5922. if (res.ok) {
  5923. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  5924. loadBridge();
  5925. fetchData(false);
  5926. } else {
  5927. const err = await res.json();
  5928. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  5929. }
  5930. } catch (err) {
  5931. showToast('Error', err.message, 'error');
  5932. }
  5933. }
  5934. // ----------------- Bridge IP Assignments -----------------
  5935. function openAddBridgeIPModal(id, name) {
  5936. document.getElementById('bridge-ip-modal-id').value = id;
  5937. document.getElementById('bridge-ip-modal-sub').innerText = name;
  5938. document.getElementById('bridge-ip-modal-cidr').value = '';
  5939. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  5940. }
  5941. function closeBridgeIPModal() {
  5942. document.getElementById('bridge-ip-modal').classList.add('hidden');
  5943. }
  5944. async function submitAddBridgeIP(e) {
  5945. e.preventDefault();
  5946. const id = document.getElementById('bridge-ip-modal-id').value;
  5947. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  5948. try {
  5949. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  5950. method: 'POST',
  5951. headers: { 'Content-Type': 'application/json' },
  5952. body: JSON.stringify({ ip })
  5953. });
  5954. if (res.ok) {
  5955. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  5956. closeBridgeIPModal();
  5957. loadBridge();
  5958. fetchData(false);
  5959. } else {
  5960. const err = await res.json();
  5961. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  5962. }
  5963. } catch (err) {
  5964. showToast('Error', err.message, 'error');
  5965. }
  5966. }
  5967. async function deleteBridgeIP(id, ip) {
  5968. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  5969. try {
  5970. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  5971. method: 'DELETE',
  5972. headers: { 'Content-Type': 'application/json' },
  5973. body: JSON.stringify({ ip })
  5974. });
  5975. if (res.ok) {
  5976. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  5977. loadBridge();
  5978. fetchData(false);
  5979. }
  5980. } catch (err) {
  5981. showToast('Error', err.message, 'error');
  5982. }
  5983. }
  5984. // ----------------- Bridge Ports -----------------
  5985. function renderBridgePorts() {
  5986. const tbody = document.getElementById('bridge-ports-table-body');
  5987. const empty = document.getElementById('bridge-empty-ports');
  5988. const countBadge = document.getElementById('bridge-ports-count-badge');
  5989. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  5990. if (!tbody) return;
  5991. tbody.innerHTML = '';
  5992. // Update filter select
  5993. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  5994. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  5995. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  5996. if (ports.length === 0) {
  5997. empty?.classList.remove('hidden');
  5998. return;
  5999. }
  6000. empty?.classList.add('hidden');
  6001. ports.forEach((p, idx) => {
  6002. const tr = document.createElement('tr');
  6003. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  6004. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  6005. tr.innerHTML = `
  6006. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  6007. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  6008. <td class="py-2.5 px-3 font-bold text-white text-sm">
  6009. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  6010. </td>
  6011. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  6012. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  6013. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  6014. <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>
  6015. <td class="py-2.5 px-3">
  6016. ${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>'}
  6017. </td>
  6018. <td class="py-2.5 px-3">
  6019. <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>
  6020. </td>
  6021. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  6022. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6023. <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>
  6024. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6025. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6026. </td>
  6027. `;
  6028. tbody.appendChild(tr);
  6029. });
  6030. }
  6031. function openAddBridgePortModal() {
  6032. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  6033. document.getElementById('bridge-port-modal-id').value = '';
  6034. populateBridgeSelect('bridge-port-modal-bridge');
  6035. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  6036. document.getElementById('bridge-port-modal-pvid').value = '1';
  6037. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  6038. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  6039. document.getElementById('bridge-port-modal-horizon').value = '0';
  6040. document.getElementById('bridge-port-modal-pathcost').value = '10';
  6041. document.getElementById('bridge-port-modal-priority').value = '128';
  6042. document.getElementById('bridge-port-modal-learn').checked = true;
  6043. document.getElementById('bridge-port-modal-comment').value = '';
  6044. document.getElementById('bridge-port-modal-disabled').checked = false;
  6045. document.getElementById('bridge-port-modal').classList.remove('hidden');
  6046. }
  6047. function openEditBridgePortModal(id) {
  6048. const p = (state.bridgePorts || []).find(x => x.id === id);
  6049. if (!p) return;
  6050. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  6051. document.getElementById('bridge-port-modal-id').value = p.id;
  6052. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  6053. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  6054. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  6055. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  6056. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  6057. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  6058. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  6059. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  6060. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  6061. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  6062. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  6063. document.getElementById('bridge-port-modal').classList.remove('hidden');
  6064. }
  6065. function closeBridgePortModal() {
  6066. document.getElementById('bridge-port-modal').classList.add('hidden');
  6067. }
  6068. async function submitSaveBridgePort(e) {
  6069. e.preventDefault();
  6070. const id = document.getElementById('bridge-port-modal-id').value;
  6071. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  6072. const iface = document.getElementById('bridge-port-modal-interface').value;
  6073. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  6074. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  6075. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  6076. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  6077. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  6078. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  6079. const learn = document.getElementById('bridge-port-modal-learn').checked;
  6080. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  6081. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  6082. try {
  6083. const res = await fetch(`${API_BASE}/bridge/ports`, {
  6084. method: 'POST',
  6085. headers: { 'Content-Type': 'application/json' },
  6086. body: JSON.stringify({
  6087. id,
  6088. bridge,
  6089. interface: iface,
  6090. pvid,
  6091. frame_types: frameTypes,
  6092. ingress_filtering: ingressFiltering,
  6093. horizon,
  6094. path_cost: pathCost,
  6095. priority,
  6096. learn,
  6097. comment,
  6098. disabled
  6099. })
  6100. });
  6101. if (res.ok) {
  6102. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  6103. closeBridgePortModal();
  6104. loadBridge();
  6105. fetchData(false);
  6106. } else {
  6107. const err = await res.json();
  6108. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  6109. }
  6110. } catch (err) {
  6111. showToast('Error', err.message, 'error');
  6112. }
  6113. }
  6114. async function toggleBridgePortState(id, disabled) {
  6115. try {
  6116. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  6117. method: 'POST',
  6118. headers: { 'Content-Type': 'application/json' },
  6119. body: JSON.stringify({ disabled })
  6120. });
  6121. if (res.ok) {
  6122. loadBridge();
  6123. fetchData(false);
  6124. }
  6125. } catch (err) {
  6126. showToast('Error', err.message, 'error');
  6127. }
  6128. }
  6129. async function deleteBridgePort(id) {
  6130. const p = (state.bridgePorts || []).find(x => x.id === id);
  6131. const iface = p ? p.interface : id;
  6132. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  6133. try {
  6134. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6135. if (res.ok) {
  6136. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  6137. loadBridge();
  6138. fetchData(false);
  6139. }
  6140. } catch (err) {
  6141. showToast('Error', err.message, 'error');
  6142. }
  6143. }
  6144. // ----------------- Bridge VLANs -----------------
  6145. function renderBridgeVLANs() {
  6146. const tbody = document.getElementById('bridge-vlans-table-body');
  6147. const empty = document.getElementById('bridge-empty-vlans');
  6148. const countBadge = document.getElementById('bridge-vlans-count-badge');
  6149. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  6150. if (!tbody) return;
  6151. tbody.innerHTML = '';
  6152. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  6153. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  6154. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  6155. if (vlans.length === 0) {
  6156. empty?.classList.remove('hidden');
  6157. return;
  6158. }
  6159. empty?.classList.add('hidden');
  6160. vlans.forEach((v, idx) => {
  6161. const tr = document.createElement('tr');
  6162. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  6163. const taggedHtml = (v.tagged && v.tagged.length > 0)
  6164. ? 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(' ')
  6165. : '<span class="text-slate-600">none</span>';
  6166. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  6167. ? 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(' ')
  6168. : '<span class="text-slate-600">none</span>';
  6169. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  6170. tr.innerHTML = `
  6171. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  6172. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  6173. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  6174. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  6175. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  6176. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  6177. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  6178. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6179. <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>
  6180. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6181. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6182. </td>
  6183. `;
  6184. tbody.appendChild(tr);
  6185. });
  6186. }
  6187. function openAddBridgeVLANModal() {
  6188. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  6189. document.getElementById('bridge-vlan-modal-id').value = '';
  6190. populateBridgeSelect('bridge-vlan-modal-bridge');
  6191. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  6192. document.getElementById('bridge-vlan-modal-comment').value = '';
  6193. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  6194. updateBridgeVlanPortCheckboxes();
  6195. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  6196. }
  6197. function openEditBridgeVLANModal(id) {
  6198. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  6199. if (!v) return;
  6200. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  6201. document.getElementById('bridge-vlan-modal-id').value = v.id;
  6202. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  6203. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  6204. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  6205. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  6206. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  6207. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  6208. }
  6209. function closeBridgeVlanModal() {
  6210. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  6211. }
  6212. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  6213. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  6214. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  6215. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  6216. if (!taggedBox || !untaggedBox) return;
  6217. // Ports belonging to the selected bridge
  6218. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  6219. if (memberPorts.length === 0) {
  6220. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  6221. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  6222. return;
  6223. }
  6224. taggedBox.innerHTML = memberPorts.map(p => `
  6225. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  6226. <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">
  6227. <span>${p.interface}</span>
  6228. </label>
  6229. `).join('');
  6230. untaggedBox.innerHTML = memberPorts.map(p => `
  6231. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  6232. <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">
  6233. <span>${p.interface}</span>
  6234. </label>
  6235. `).join('');
  6236. }
  6237. async function submitSaveBridgeVLAN(e) {
  6238. e.preventDefault();
  6239. const id = document.getElementById('bridge-vlan-modal-id').value;
  6240. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  6241. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  6242. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  6243. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  6244. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  6245. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  6246. try {
  6247. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  6248. method: 'POST',
  6249. headers: { 'Content-Type': 'application/json' },
  6250. body: JSON.stringify({
  6251. id,
  6252. bridge,
  6253. vlan_ids: vlanIDs,
  6254. tagged,
  6255. untagged,
  6256. comment,
  6257. disabled
  6258. })
  6259. });
  6260. if (res.ok) {
  6261. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  6262. closeBridgeVlanModal();
  6263. loadBridge();
  6264. } else {
  6265. const err = await res.json();
  6266. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  6267. }
  6268. } catch (err) {
  6269. showToast('Error', err.message, 'error');
  6270. }
  6271. }
  6272. async function toggleBridgeVLANState(id, disabled) {
  6273. try {
  6274. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  6275. method: 'POST',
  6276. headers: { 'Content-Type': 'application/json' },
  6277. body: JSON.stringify({ disabled })
  6278. });
  6279. if (res.ok) loadBridge();
  6280. } catch (err) {
  6281. showToast('Error', err.message, 'error');
  6282. }
  6283. }
  6284. async function deleteBridgeVLAN(id) {
  6285. if (!confirm('Delete this bridge VLAN entry?')) return;
  6286. try {
  6287. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6288. if (res.ok) {
  6289. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  6290. loadBridge();
  6291. }
  6292. } catch (err) {
  6293. showToast('Error', err.message, 'error');
  6294. }
  6295. }
  6296. // ----------------- Hosts / MAC Table -----------------
  6297. async function loadBridgeHosts() {
  6298. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  6299. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  6300. try {
  6301. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  6302. const res = await fetch(url);
  6303. if (res.ok) {
  6304. state.bridgeHosts = await res.json();
  6305. renderBridgeHosts();
  6306. }
  6307. } catch (err) {
  6308. console.error('Failed to load bridge hosts:', err);
  6309. }
  6310. }
  6311. function renderBridgeHosts() {
  6312. const tbody = document.getElementById('bridge-hosts-table-body');
  6313. const empty = document.getElementById('bridge-empty-hosts');
  6314. const countBadge = document.getElementById('bridge-hosts-count-badge');
  6315. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  6316. if (!tbody) return;
  6317. tbody.innerHTML = '';
  6318. const hosts = (state.bridgeHosts || []).filter(h => {
  6319. if (!search) return true;
  6320. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  6321. });
  6322. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  6323. if (hosts.length === 0) {
  6324. empty?.classList.remove('hidden');
  6325. return;
  6326. }
  6327. empty?.classList.add('hidden');
  6328. hosts.forEach(h => {
  6329. const tr = document.createElement('tr');
  6330. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  6331. let flagBadges = '';
  6332. 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>';
  6333. 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>';
  6334. 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>';
  6335. tr.innerHTML = `
  6336. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  6337. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  6338. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  6339. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  6340. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  6341. <td class="py-2.5 px-3">${flagBadges}</td>
  6342. `;
  6343. tbody.appendChild(tr);
  6344. });
  6345. }
  6346. async function flushBridgeHosts() {
  6347. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  6348. if (!selBridge) {
  6349. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  6350. return;
  6351. }
  6352. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  6353. try {
  6354. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  6355. method: 'POST',
  6356. headers: { 'Content-Type': 'application/json' },
  6357. body: JSON.stringify({ bridge: selBridge })
  6358. });
  6359. if (res.ok) {
  6360. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  6361. loadBridgeHosts();
  6362. }
  6363. } catch (err) {
  6364. showToast('Error', err.message, 'error');
  6365. }
  6366. }
  6367. // ----------------- Helpers -----------------
  6368. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  6369. const sel = document.getElementById(selectId);
  6370. if (!sel) return;
  6371. const prevVal = currentVal || sel.value;
  6372. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  6373. (state.bridges || []).forEach(b => {
  6374. const opt = document.createElement('option');
  6375. opt.value = b.name;
  6376. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  6377. if (b.name === prevVal) opt.selected = true;
  6378. sel.appendChild(opt);
  6379. });
  6380. }
  6381. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  6382. const sel = document.getElementById(selectId);
  6383. if (!sel) return;
  6384. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  6385. // 1. Physical Interfaces
  6386. const grpPhys = document.createElement('optgroup');
  6387. grpPhys.label = 'Physical Interfaces';
  6388. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  6389. const opt = document.createElement('option');
  6390. opt.value = i.name;
  6391. opt.innerText = `${i.name} (${i.role || i.type})`;
  6392. if (i.name === currentVal) opt.selected = true;
  6393. grpPhys.appendChild(opt);
  6394. });
  6395. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  6396. // 2. VLAN Sub-interfaces
  6397. const grpVlans = document.createElement('optgroup');
  6398. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  6399. (state.vlans || []).forEach(v => {
  6400. const opt = document.createElement('option');
  6401. opt.value = v.name;
  6402. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  6403. if (v.name === currentVal) opt.selected = true;
  6404. grpVlans.appendChild(opt);
  6405. });
  6406. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  6407. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  6408. const grpEoip = document.createElement('optgroup');
  6409. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  6410. (state.eoipTunnels || []).forEach(t => {
  6411. const opt = document.createElement('option');
  6412. opt.value = t.name;
  6413. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  6414. if (t.name === currentVal) opt.selected = true;
  6415. grpEoip.appendChild(opt);
  6416. });
  6417. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  6418. }
  6419. // -------------------------------------------------------------
  6420. // Routing Filters Management (/routing filter)
  6421. // -------------------------------------------------------------
  6422. function renderRoutingFilters() {
  6423. const tbody = document.getElementById('routing-filters-table-body');
  6424. if (!tbody) return;
  6425. const empty = document.getElementById('routing-filters-empty');
  6426. const countBadge = document.getElementById('routing-filters-count-badge');
  6427. const navBadge = document.getElementById('badge-filters-count');
  6428. const chainSelect = document.getElementById('routing-filter-chain-select');
  6429. const allRules = state.routingFilters || [];
  6430. if (navBadge) navBadge.innerText = allRules.length;
  6431. // Populate chain filter select options dynamically
  6432. if (chainSelect) {
  6433. const currentVal = state.filterChainSelected || 'all';
  6434. const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
  6435. chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
  6436. uniqueChains.map(ch => {
  6437. const count = allRules.filter(r => r.chain === ch).length;
  6438. return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
  6439. }).join('');
  6440. chainSelect.value = currentVal;
  6441. }
  6442. // Filter rules by selected chain
  6443. const filteredRules = (state.filterChainSelected && state.filterChainSelected !== 'all')
  6444. ? allRules.filter(r => r.chain === state.filterChainSelected)
  6445. : allRules.slice();
  6446. // Sort by chain then rule_order
  6447. filteredRules.sort((a, b) => {
  6448. if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
  6449. return (a.rule_order || 0) - (b.rule_order || 0);
  6450. });
  6451. if (countBadge) countBadge.innerText = `${filteredRules.length} Rules`;
  6452. if (filteredRules.length === 0) {
  6453. tbody.innerHTML = '';
  6454. if (empty) empty.classList.remove('hidden');
  6455. return;
  6456. }
  6457. if (empty) empty.classList.add('hidden');
  6458. tbody.innerHTML = filteredRules.map(r => {
  6459. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  6460. const flagX = r.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  6461. let actionBadge = '';
  6462. if (r.action === 'accept') {
  6463. 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>';
  6464. } else if (r.action === 'discard') {
  6465. 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>';
  6466. } else if (r.action === 'reject') {
  6467. 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>';
  6468. } else {
  6469. 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>`;
  6470. }
  6471. // Prefix match
  6472. let matchPfx = '';
  6473. if (r.prefix) {
  6474. matchPfx = `<span class="font-bold text-white">${escapeHtml(r.prefix)}</span>`;
  6475. if (r.prefix_len) {
  6476. matchPfx += ` <span class="text-slate-400 text-[11px] font-normal">[${escapeHtml(r.prefix_len)}]</span>`;
  6477. }
  6478. } else {
  6479. matchPfx = '<span class="text-slate-500 italic">any prefix</span>';
  6480. }
  6481. // Other matches
  6482. const matchExtra = [];
  6483. if (r.match_protocol && r.match_protocol !== 'any') {
  6484. 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>`);
  6485. }
  6486. if (r.match_as_path) {
  6487. 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>`);
  6488. }
  6489. if (r.match_community) {
  6490. 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>`);
  6491. }
  6492. const matchExtraHtml = matchExtra.length > 0 ? matchExtra.join(' ') : '<span class="text-slate-600">-</span>';
  6493. // Set modifications
  6494. const setBadges = [];
  6495. if (r.set_local_pref > 0) {
  6496. 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>`);
  6497. }
  6498. if (r.set_metric > 0) {
  6499. 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>`);
  6500. }
  6501. if (r.set_as_prepend > 0) {
  6502. 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>`);
  6503. }
  6504. if (r.set_community) {
  6505. 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>`);
  6506. }
  6507. if (r.set_next_hop) {
  6508. 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>`);
  6509. }
  6510. const setHtml = setBadges.length > 0 ? setBadges.join(' ') : '<span class="text-slate-600">-</span>';
  6511. return `
  6512. <tr class="hover:bg-slate-800/40 transition">
  6513. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagX}</td>
  6514. <td class="py-2.5 px-3 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  6515. <td class="py-2.5 px-3">
  6516. <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>
  6517. </td>
  6518. <td class="py-2.5 px-3">${actionBadge}</td>
  6519. <td class="py-2.5 px-3 font-mono">${matchPfx}</td>
  6520. <td class="py-2.5 px-3 space-x-1">${matchExtraHtml}</td>
  6521. <td class="py-2.5 px-3 space-x-1 font-mono">${setHtml}</td>
  6522. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  6523. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  6524. <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'}">
  6525. ${r.disabled ? 'Enable' : 'Disable'}
  6526. </button>
  6527. <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">
  6528. Edit
  6529. </button>
  6530. <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">
  6531. Delete
  6532. </button>
  6533. </td>
  6534. </tr>
  6535. `;
  6536. }).join('');
  6537. }
  6538. function filterRoutingFiltersByChain(chain) {
  6539. state.filterChainSelected = chain;
  6540. renderRoutingFilters();
  6541. }
  6542. function openAddRoutingFilterModal(defaultChain = '') {
  6543. const form = document.getElementById('routing-filter-form');
  6544. if (form) form.reset();
  6545. const idEl = document.getElementById('modal-rf-id');
  6546. if (idEl) idEl.value = '';
  6547. const titleEl = document.getElementById('modal-rf-title');
  6548. if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
  6549. const chainEl = document.getElementById('modal-rf-chain');
  6550. if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
  6551. const orderEl = document.getElementById('modal-rf-order');
  6552. if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
  6553. const actEl = document.getElementById('modal-rf-action');
  6554. if (actEl) actEl.value = 'accept';
  6555. const protoEl = document.getElementById('modal-rf-protocol');
  6556. if (protoEl) protoEl.value = 'any';
  6557. const disEl = document.getElementById('modal-rf-disabled');
  6558. if (disEl) disEl.checked = false;
  6559. const modal = document.getElementById('modal-routing-filter');
  6560. if (modal) modal.classList.remove('hidden');
  6561. }
  6562. function openEditRoutingFilterModal(id) {
  6563. const r = (state.routingFilters || []).find(item => item.id === id);
  6564. if (!r) return;
  6565. const idEl = document.getElementById('modal-rf-id');
  6566. if (idEl) idEl.value = r.id;
  6567. const titleEl = document.getElementById('modal-rf-title');
  6568. if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
  6569. const chainEl = document.getElementById('modal-rf-chain');
  6570. if (chainEl) chainEl.value = r.chain || '';
  6571. const orderEl = document.getElementById('modal-rf-order');
  6572. if (orderEl) orderEl.value = r.rule_order || 10;
  6573. const actEl = document.getElementById('modal-rf-action');
  6574. if (actEl) actEl.value = r.action || 'accept';
  6575. const pfxEl = document.getElementById('modal-rf-prefix');
  6576. if (pfxEl) pfxEl.value = r.prefix || '';
  6577. const pfxLenEl = document.getElementById('modal-rf-prefix-len');
  6578. if (pfxLenEl) pfxLenEl.value = r.prefix_len || '';
  6579. const protoEl = document.getElementById('modal-rf-protocol');
  6580. if (protoEl) protoEl.value = r.match_protocol || 'any';
  6581. const aspEl = document.getElementById('modal-rf-as-path');
  6582. if (aspEl) aspEl.value = r.match_as_path || '';
  6583. const commEl = document.getElementById('modal-rf-community');
  6584. if (commEl) commEl.value = r.match_community || '';
  6585. const lpEl = document.getElementById('modal-rf-set-local-pref');
  6586. if (lpEl) lpEl.value = r.set_local_pref || '';
  6587. const metEl = document.getElementById('modal-rf-set-metric');
  6588. if (metEl) metEl.value = r.set_metric || '';
  6589. const prepEl = document.getElementById('modal-rf-set-as-prepend');
  6590. if (prepEl) prepEl.value = r.set_as_prepend || '';
  6591. const setCommEl = document.getElementById('modal-rf-set-community');
  6592. if (setCommEl) setCommEl.value = r.set_community || '';
  6593. const nhEl = document.getElementById('modal-rf-set-next-hop');
  6594. if (nhEl) nhEl.value = r.set_next_hop || '';
  6595. const comEl = document.getElementById('modal-rf-comment');
  6596. if (comEl) comEl.value = r.comment || '';
  6597. const disEl = document.getElementById('modal-rf-disabled');
  6598. if (disEl) disEl.checked = !!r.disabled;
  6599. const modal = document.getElementById('modal-routing-filter');
  6600. if (modal) modal.classList.remove('hidden');
  6601. }
  6602. function closeRoutingFilterModal() {
  6603. const modal = document.getElementById('modal-routing-filter');
  6604. if (modal) modal.classList.add('hidden');
  6605. }
  6606. async function submitRoutingFilter(e) {
  6607. e.preventDefault();
  6608. const payload = {
  6609. id: document.getElementById('modal-rf-id').value,
  6610. chain: document.getElementById('modal-rf-chain').value.trim(),
  6611. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  6612. action: document.getElementById('modal-rf-action').value,
  6613. prefix: document.getElementById('modal-rf-prefix').value.trim(),
  6614. prefix_len: document.getElementById('modal-rf-prefix-len').value.trim(),
  6615. match_protocol: document.getElementById('modal-rf-protocol').value,
  6616. match_as_path: document.getElementById('modal-rf-as-path').value.trim(),
  6617. match_community: document.getElementById('modal-rf-community').value.trim(),
  6618. set_local_pref: parseInt(document.getElementById('modal-rf-set-local-pref').value, 10) || 0,
  6619. set_metric: parseInt(document.getElementById('modal-rf-set-metric').value, 10) || 0,
  6620. set_as_prepend: parseInt(document.getElementById('modal-rf-set-as-prepend').value, 10) || 0,
  6621. set_community: document.getElementById('modal-rf-set-community').value.trim(),
  6622. set_next_hop: document.getElementById('modal-rf-set-next-hop').value.trim(),
  6623. comment: document.getElementById('modal-rf-comment').value.trim(),
  6624. disabled: document.getElementById('modal-rf-disabled').checked
  6625. };
  6626. try {
  6627. const res = await fetch(`${API_BASE}/routing/filters`, {
  6628. method: 'POST',
  6629. headers: { 'Content-Type': 'application/json' },
  6630. body: JSON.stringify(payload)
  6631. });
  6632. if (res.ok) {
  6633. closeRoutingFilterModal();
  6634. showToast('Success', 'Routing filter rule saved', 'success');
  6635. loadDynamicRouting();
  6636. } else {
  6637. const err = await res.json();
  6638. showToast('Error', err.error || 'Failed to save filter rule', 'error');
  6639. }
  6640. } catch (err) {
  6641. showToast('Error', err.message, 'error');
  6642. }
  6643. }
  6644. async function deleteRoutingFilter(id) {
  6645. if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
  6646. try {
  6647. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6648. if (res.ok) {
  6649. showToast('Deleted', 'Routing filter rule removed', 'info');
  6650. loadDynamicRouting();
  6651. } else {
  6652. const err = await res.json();
  6653. showToast('Error', err.error || 'Failed to delete rule', 'error');
  6654. }
  6655. } catch (err) {
  6656. showToast('Error', err.message, 'error');
  6657. }
  6658. }
  6659. async function toggleRoutingFilterState(id, disabled) {
  6660. try {
  6661. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
  6662. method: 'POST',
  6663. headers: { 'Content-Type': 'application/json' },
  6664. body: JSON.stringify({ disabled })
  6665. });
  6666. if (res.ok) {
  6667. showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  6668. loadDynamicRouting();
  6669. } else {
  6670. const err = await res.json();
  6671. showToast('Error', err.error || 'Failed to toggle rule state', 'error');
  6672. }
  6673. } catch (err) {
  6674. showToast('Error', err.message, 'error');
  6675. }
  6676. }
  6677. // ==========================================
  6678. // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
  6679. // ==========================================
  6680. function loadToolsView() {
  6681. populateToolsInterfaces();
  6682. switchToolsSubTab(state.activeToolsSubTab || 'ping');
  6683. }
  6684. function populateToolsInterfaces() {
  6685. const pingSel = document.getElementById('tools-ping-iface');
  6686. const traceSel = document.getElementById('tools-tr-iface');
  6687. let opts = '<option value="">Auto (Default Route)</option>';
  6688. if (Array.isArray(state.interfaces)) {
  6689. state.interfaces.forEach(iface => {
  6690. if (iface.name) {
  6691. opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
  6692. }
  6693. });
  6694. }
  6695. if (pingSel) {
  6696. const cur = pingSel.value;
  6697. pingSel.innerHTML = opts;
  6698. if (cur) pingSel.value = cur;
  6699. }
  6700. if (traceSel) {
  6701. const cur = traceSel.value;
  6702. traceSel.innerHTML = opts;
  6703. if (cur) traceSel.value = cur;
  6704. }
  6705. }
  6706. function switchToolsSubTab(subTab) {
  6707. state.activeToolsSubTab = subTab;
  6708. const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
  6709. tabs.forEach(t => {
  6710. const btn = document.getElementById(`tools-subtab-btn-${t}`);
  6711. const view = document.getElementById(`tools-view-${t}`);
  6712. if (btn) {
  6713. if (t === subTab) {
  6714. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-amber-400 text-amber-300 transition flex items-center gap-2 whitespace-nowrap';
  6715. } else {
  6716. 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';
  6717. }
  6718. }
  6719. if (view) {
  6720. if (t === subTab) {
  6721. view.classList.remove('hidden');
  6722. } else {
  6723. view.classList.add('hidden');
  6724. }
  6725. }
  6726. });
  6727. }
  6728. function setPortPreset(port) {
  6729. const input = document.getElementById('tools-port-num');
  6730. if (input) input.value = port;
  6731. }
  6732. let pingAbortController = null;
  6733. let tracerouteAbortController = null;
  6734. function clearPingTable() {
  6735. const tbody = document.getElementById('tools-ping-tbody');
  6736. if (tbody) tbody.innerHTML = '';
  6737. const rawEl = document.getElementById('tools-ping-raw');
  6738. if (rawEl) rawEl.innerText = '';
  6739. const sentEl = document.getElementById('tools-ping-stat-sent');
  6740. if (sentEl) sentEl.innerText = '0';
  6741. const recvEl = document.getElementById('tools-ping-stat-recv');
  6742. if (recvEl) recvEl.innerText = '0';
  6743. const lossEl = document.getElementById('tools-ping-stat-loss');
  6744. if (lossEl) lossEl.innerText = '0%';
  6745. const avgEl = document.getElementById('tools-ping-stat-avg');
  6746. if (avgEl) avgEl.innerText = '0 ms';
  6747. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  6748. if (minMaxEl) minMaxEl.innerText = '-';
  6749. const badge = document.getElementById('tools-ping-status-badge');
  6750. if (badge) {
  6751. badge.className = '';
  6752. badge.innerText = '';
  6753. }
  6754. }
  6755. function clearTracerouteTable() {
  6756. const tbody = document.getElementById('tools-tr-tbody');
  6757. if (tbody) tbody.innerHTML = '';
  6758. const rawEl = document.getElementById('tools-tr-raw');
  6759. if (rawEl) rawEl.innerText = '';
  6760. const statHops = document.getElementById('tools-tr-hops-count');
  6761. if (statHops) statHops.innerText = '0 Hops';
  6762. }
  6763. function resetPingButton() {
  6764. const btn = document.getElementById('tools-ping-btn');
  6765. const btnText = document.getElementById('tools-ping-btn-text');
  6766. const spinner = document.getElementById('tools-ping-spinner');
  6767. if (btn) {
  6768. btn.disabled = false;
  6769. btn.className = 'px-5 py-2 rounded-lg font-semibold text-xs bg-amber-500 hover:bg-amber-400 text-slate-950 shadow-lg shadow-amber-500/20 transition flex items-center gap-2';
  6770. }
  6771. if (btnText) btnText.innerText = 'Start Ping';
  6772. if (spinner) spinner.classList.add('hidden');
  6773. }
  6774. function setPingRunningButton() {
  6775. const btn = document.getElementById('tools-ping-btn');
  6776. const btnText = document.getElementById('tools-ping-btn-text');
  6777. const spinner = document.getElementById('tools-ping-spinner');
  6778. if (btn) {
  6779. btn.disabled = false;
  6780. btn.className = 'px-5 py-2 rounded-lg font-semibold text-xs bg-rose-600 hover:bg-rose-500 text-white shadow-lg shadow-rose-600/30 transition flex items-center gap-2';
  6781. }
  6782. if (btnText) btnText.innerText = 'Stop Ping';
  6783. if (spinner) spinner.classList.remove('hidden');
  6784. }
  6785. function resetTracerouteButton() {
  6786. const btn = document.getElementById('tools-tr-btn');
  6787. const btnText = document.getElementById('tools-tr-btn-text');
  6788. const spinner = document.getElementById('tools-tr-spinner');
  6789. if (btn) {
  6790. btn.disabled = false;
  6791. btn.className = 'px-5 py-2 rounded-lg font-semibold text-xs bg-amber-500 hover:bg-amber-400 text-slate-950 shadow-lg shadow-amber-500/20 transition flex items-center gap-2';
  6792. }
  6793. if (btnText) btnText.innerText = 'Start Traceroute';
  6794. if (spinner) spinner.classList.add('hidden');
  6795. }
  6796. function setTracerouteRunningButton() {
  6797. const btn = document.getElementById('tools-tr-btn');
  6798. const btnText = document.getElementById('tools-tr-btn-text');
  6799. const spinner = document.getElementById('tools-tr-spinner');
  6800. if (btn) {
  6801. btn.disabled = false;
  6802. btn.className = 'px-5 py-2 rounded-lg font-semibold text-xs bg-rose-600 hover:bg-rose-500 text-white shadow-lg shadow-rose-600/30 transition flex items-center gap-2';
  6803. }
  6804. if (btnText) btnText.innerText = 'Stop Traceroute';
  6805. if (spinner) spinner.classList.remove('hidden');
  6806. }
  6807. async function executePing(e) {
  6808. if (e) e.preventDefault();
  6809. // If already running, clicking the button stops the stream!
  6810. if (pingAbortController) {
  6811. pingAbortController.abort();
  6812. pingAbortController = null;
  6813. resetPingButton();
  6814. showToast('Ping Stopped', 'Live ping stopped by user', 'info');
  6815. return;
  6816. }
  6817. const target = document.getElementById('tools-ping-target')?.value?.trim();
  6818. const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
  6819. const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
  6820. const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '3', 10);
  6821. const iface = document.getElementById('tools-ping-iface')?.value || '';
  6822. const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
  6823. if (!target) {
  6824. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  6825. return;
  6826. }
  6827. clearPingTable();
  6828. const resCard = document.getElementById('tools-ping-results');
  6829. if (resCard) resCard.classList.remove('hidden');
  6830. pingAbortController = new AbortController();
  6831. setPingRunningButton();
  6832. try {
  6833. const res = await fetch(`${API_BASE}/tools/ping/stream`, {
  6834. method: 'POST',
  6835. headers: { 'Content-Type': 'application/json' },
  6836. body: JSON.stringify({
  6837. target,
  6838. count,
  6839. size,
  6840. timeout,
  6841. interface: iface,
  6842. dont_frag: dontFrag
  6843. }),
  6844. signal: pingAbortController.signal
  6845. });
  6846. if (!res.ok) {
  6847. const errText = await res.text();
  6848. showToast('Ping Error', errText || 'Failed to start live ping', 'error');
  6849. resetPingButton();
  6850. pingAbortController = null;
  6851. return;
  6852. }
  6853. const reader = res.body.getReader();
  6854. const decoder = new TextDecoder('utf-8');
  6855. let buffer = '';
  6856. while (true) {
  6857. const { done, value } = await reader.read();
  6858. if (done) break;
  6859. buffer += decoder.decode(value, { stream: true });
  6860. const blocks = buffer.split('\n\n');
  6861. buffer = blocks.pop() || '';
  6862. for (const block of blocks) {
  6863. const trimmed = block.trim();
  6864. if (!trimmed) continue;
  6865. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  6866. try {
  6867. const evt = JSON.parse(line);
  6868. handleLivePingEvent(evt);
  6869. } catch (parseErr) {
  6870. console.warn('Ping SSE parse error:', parseErr, line);
  6871. }
  6872. }
  6873. }
  6874. } catch (err) {
  6875. if (err.name === 'AbortError') {
  6876. // User aborted normally
  6877. } else {
  6878. showToast('Ping Error', err.message, 'error');
  6879. }
  6880. } finally {
  6881. pingAbortController = null;
  6882. resetPingButton();
  6883. }
  6884. }
  6885. function handleLivePingEvent(evt) {
  6886. const sentEl = document.getElementById('tools-ping-stat-sent');
  6887. const recvEl = document.getElementById('tools-ping-stat-recv');
  6888. const lossEl = document.getElementById('tools-ping-stat-loss');
  6889. const avgEl = document.getElementById('tools-ping-stat-avg');
  6890. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  6891. const badge = document.getElementById('tools-ping-status-badge');
  6892. const tbody = document.getElementById('tools-ping-tbody');
  6893. const rawEl = document.getElementById('tools-ping-raw');
  6894. if (evt.raw && rawEl) {
  6895. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  6896. rawEl.scrollTop = rawEl.scrollHeight;
  6897. }
  6898. if (evt.type === 'reply') {
  6899. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  6900. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  6901. if (lossEl && evt.packet_loss_pct !== undefined) {
  6902. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  6903. lossEl.className = evt.packet_loss_pct === 0
  6904. ? 'text-base font-bold font-mono text-emerald-400 mt-1'
  6905. : (evt.packet_loss_pct < 50 ? 'text-base font-bold font-mono text-amber-400 mt-1' : 'text-base font-bold font-mono text-rose-400 mt-1');
  6906. }
  6907. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  6908. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  6909. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  6910. }
  6911. if (badge) {
  6912. if (evt.packet_loss_pct === 0) {
  6913. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-emerald-950 text-emerald-300 border border-emerald-800/60';
  6914. badge.innerText = '100% OK';
  6915. } else {
  6916. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-amber-950 text-amber-300 border border-amber-800/60';
  6917. badge.innerText = `${evt.packet_loss_pct.toFixed(0)}% LOSS`;
  6918. }
  6919. }
  6920. if (tbody) {
  6921. const tr = document.createElement('tr');
  6922. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  6923. tr.innerHTML = `
  6924. <td class="py-2 px-3 text-slate-300">#${evt.seq}</td>
  6925. <td class="py-2 px-3 font-semibold text-white">${escapeHtml(evt.from)}</td>
  6926. <td class="py-2 px-3 text-slate-400">${evt.bytes} bytes</td>
  6927. <td class="py-2 px-3 text-slate-300">${evt.ttl}</td>
  6928. <td class="py-2 px-3 font-bold text-amber-300">${evt.time_ms.toFixed(2)} ms</td>
  6929. <td class="py-2 px-3 text-right"><span class="px-2 py-0.5 rounded text-[10px] font-bold bg-emerald-950 text-emerald-300 border border-emerald-800/60">REPLY</span></td>
  6930. `;
  6931. tbody.appendChild(tr);
  6932. }
  6933. } else if (evt.type === 'timeout') {
  6934. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  6935. if (lossEl && evt.packet_loss_pct !== undefined) {
  6936. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  6937. lossEl.className = evt.packet_loss_pct < 50 ? 'text-base font-bold font-mono text-amber-400 mt-1' : 'text-base font-bold font-mono text-rose-400 mt-1';
  6938. }
  6939. if (badge) {
  6940. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-rose-950 text-rose-300 border border-rose-800/60';
  6941. badge.innerText = `${evt.packet_loss_pct?.toFixed(0) || 100}% LOSS`;
  6942. }
  6943. if (tbody) {
  6944. const tr = document.createElement('tr');
  6945. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs opacity-75';
  6946. tr.innerHTML = `
  6947. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  6948. <td class="py-2 px-3 font-semibold text-slate-500 italic">Request timed out</td>
  6949. <td class="py-2 px-3 text-slate-600">--</td>
  6950. <td class="py-2 px-3 text-slate-600">--</td>
  6951. <td class="py-2 px-3 font-bold text-slate-500">* * *</td>
  6952. <td class="py-2 px-3 text-right"><span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span></td>
  6953. `;
  6954. tbody.appendChild(tr);
  6955. }
  6956. } else if (evt.type === 'unreach') {
  6957. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  6958. if (lossEl && evt.packet_loss_pct !== undefined) {
  6959. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  6960. lossEl.className = 'text-base font-bold font-mono text-rose-400 mt-1';
  6961. }
  6962. if (badge) {
  6963. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-rose-950 text-rose-300 border border-rose-800/60';
  6964. badge.innerText = 'UNREACHABLE';
  6965. }
  6966. if (tbody) {
  6967. const tr = document.createElement('tr');
  6968. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  6969. tr.innerHTML = `
  6970. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  6971. <td class="py-2 px-3 font-semibold text-rose-400">${escapeHtml(evt.from || 'Gateway')}</td>
  6972. <td class="py-2 px-3 text-slate-600">--</td>
  6973. <td class="py-2 px-3 text-slate-600">--</td>
  6974. <td class="py-2 px-3 font-bold text-rose-400 text-xs">${escapeHtml(evt.message || 'Unreachable')}</td>
  6975. <td class="py-2 px-3 text-right"><span class="px-2 py-0.5 rounded text-[10px] font-bold bg-rose-950 text-rose-300 border border-rose-800/60">UNREACH</span></td>
  6976. `;
  6977. tbody.appendChild(tr);
  6978. }
  6979. } else if (evt.type === 'stats') {
  6980. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  6981. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  6982. if (lossEl && evt.packet_loss_pct !== undefined) lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  6983. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  6984. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  6985. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  6986. }
  6987. } else if (evt.type === 'done') {
  6988. showToast('Ping Finished', `Sent ${evt.packets_sent}, received ${evt.packets_recv} (${evt.packet_loss_pct?.toFixed(0)}% loss)`, evt.packet_loss_pct === 0 ? 'success' : 'info');
  6989. }
  6990. }
  6991. async function executeTraceroute(e) {
  6992. if (e) e.preventDefault();
  6993. if (tracerouteAbortController) {
  6994. tracerouteAbortController.abort();
  6995. tracerouteAbortController = null;
  6996. resetTracerouteButton();
  6997. showToast('Traceroute Stopped', 'Traceroute stopped by user', 'info');
  6998. return;
  6999. }
  7000. const target = document.getElementById('tools-tr-target')?.value?.trim();
  7001. const maxHops = parseInt(document.getElementById('tools-tr-maxhops')?.value || '15', 10);
  7002. const protocol = document.getElementById('tools-tr-proto')?.value || 'icmp';
  7003. const iface = document.getElementById('tools-tr-iface')?.value || '';
  7004. const resolve = document.getElementById('tools-tr-resolve')?.checked || false;
  7005. if (!target) {
  7006. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  7007. return;
  7008. }
  7009. clearTracerouteTable();
  7010. const resCard = document.getElementById('tools-tr-results');
  7011. if (resCard) resCard.classList.remove('hidden');
  7012. tracerouteAbortController = new AbortController();
  7013. setTracerouteRunningButton();
  7014. try {
  7015. const res = await fetch(`${API_BASE}/tools/traceroute/stream`, {
  7016. method: 'POST',
  7017. headers: { 'Content-Type': 'application/json' },
  7018. body: JSON.stringify({
  7019. target,
  7020. max_hops: maxHops,
  7021. protocol,
  7022. interface: iface,
  7023. resolve
  7024. }),
  7025. signal: tracerouteAbortController.signal
  7026. });
  7027. if (!res.ok) {
  7028. const errText = await res.text();
  7029. showToast('Traceroute Error', errText || 'Failed to start traceroute', 'error');
  7030. resetTracerouteButton();
  7031. tracerouteAbortController = null;
  7032. return;
  7033. }
  7034. const reader = res.body.getReader();
  7035. const decoder = new TextDecoder('utf-8');
  7036. let buffer = '';
  7037. while (true) {
  7038. const { done, value } = await reader.read();
  7039. if (done) break;
  7040. buffer += decoder.decode(value, { stream: true });
  7041. const blocks = buffer.split('\n\n');
  7042. buffer = blocks.pop() || '';
  7043. for (const block of blocks) {
  7044. const trimmed = block.trim();
  7045. if (!trimmed) continue;
  7046. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  7047. try {
  7048. const evt = JSON.parse(line);
  7049. handleLiveTracerouteEvent(evt);
  7050. } catch (parseErr) {
  7051. console.warn('Traceroute SSE parse error:', parseErr, line);
  7052. }
  7053. }
  7054. }
  7055. } catch (err) {
  7056. if (err.name === 'AbortError') {
  7057. // User aborted normally
  7058. } else {
  7059. showToast('Traceroute Error', err.message, 'error');
  7060. }
  7061. } finally {
  7062. tracerouteAbortController = null;
  7063. resetTracerouteButton();
  7064. }
  7065. }
  7066. function handleLiveTracerouteEvent(evt) {
  7067. const statHops = document.getElementById('tools-tr-hops-count');
  7068. const tbody = document.getElementById('tools-tr-tbody');
  7069. const rawEl = document.getElementById('tools-tr-raw');
  7070. if (evt.raw && rawEl) {
  7071. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  7072. rawEl.scrollTop = rawEl.scrollHeight;
  7073. }
  7074. if (evt.hops_count !== undefined && statHops) {
  7075. statHops.innerText = `${evt.hops_count} Hops`;
  7076. }
  7077. if (evt.type === 'hop' && evt.hop && tbody) {
  7078. const h = evt.hop;
  7079. const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
  7080. const rtt1 = Array.isArray(h.times_ms) && h.times_ms[0] ? `${h.times_ms[0]} ms` : (isTimeout ? '*' : '--');
  7081. const rtt2 = Array.isArray(h.times_ms) && h.times_ms[1] ? `${h.times_ms[1]} ms` : (isTimeout ? '*' : '--');
  7082. const displayHost = h.host && h.host !== h.ip ? `${escapeHtml(h.host)} (${escapeHtml(h.ip || '')})` : escapeHtml(h.ip || (isTimeout ? 'Request timed out' : '--'));
  7083. const tr = document.createElement('tr');
  7084. tr.className = `hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}`;
  7085. tr.innerHTML = `
  7086. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  7087. <td class="py-2.5 px-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${displayHost}</td>
  7088. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt1)}</td>
  7089. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt2)}</td>
  7090. <td class="py-2.5 px-3 text-right">
  7091. ${isTimeout
  7092. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
  7093. : '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-emerald-950 text-emerald-300 border border-emerald-800/60">OK</span>'}
  7094. </td>
  7095. `;
  7096. tbody.appendChild(tr);
  7097. } else if (evt.type === 'done') {
  7098. showToast('Traceroute Finished', `Traced ${evt.hops_count || 0} hops`, 'info');
  7099. }
  7100. }
  7101. async function executeMTR(e) {
  7102. if (e) e.preventDefault();
  7103. const target = document.getElementById('tools-mtr-target')?.value?.trim();
  7104. const cycles = parseInt(document.getElementById('tools-mtr-count')?.value || '3', 10);
  7105. if (!target) {
  7106. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  7107. return;
  7108. }
  7109. const btn = document.getElementById('tools-mtr-btn');
  7110. const spinner = document.getElementById('tools-mtr-spinner');
  7111. if (btn) btn.disabled = true;
  7112. if (spinner) spinner.classList.remove('hidden');
  7113. try {
  7114. const res = await fetch(`${API_BASE}/tools/mtr`, {
  7115. method: 'POST',
  7116. headers: { 'Content-Type': 'application/json' },
  7117. body: JSON.stringify({ target, count: cycles })
  7118. });
  7119. const data = await res.json();
  7120. if (!res.ok) {
  7121. showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
  7122. return;
  7123. }
  7124. const resCard = document.getElementById('tools-mtr-results');
  7125. if (resCard) resCard.classList.remove('hidden');
  7126. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  7127. const statHops = document.getElementById('tools-mtr-hops-count');
  7128. if (statHops) statHops.innerText = `${hopsCount} Hops`;
  7129. const tbody = document.getElementById('tools-mtr-tbody');
  7130. if (tbody) {
  7131. if (hopsCount > 0) {
  7132. tbody.innerHTML = data.hops.map(h => {
  7133. const lossClass = h.loss_pct === 0 ? 'text-emerald-400 font-bold' : (h.loss_pct < 20 ? 'text-amber-400 font-bold' : 'text-rose-400 font-bold');
  7134. return `
  7135. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  7136. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  7137. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
  7138. <td class="py-2.5 px-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
  7139. <td class="py-2.5 px-3 text-slate-300">${h.sent}</td>
  7140. <td class="py-2.5 px-3 text-slate-300">${h.last_ms.toFixed(1)}</td>
  7141. <td class="py-2.5 px-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)}</td>
  7142. <td class="py-2.5 px-3 text-emerald-400">${h.best_ms.toFixed(1)}</td>
  7143. <td class="py-2.5 px-3 text-rose-400">${h.wrst_ms.toFixed(1)}</td>
  7144. <td class="py-2.5 px-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
  7145. </tr>
  7146. `;
  7147. }).join('');
  7148. } else {
  7149. tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
  7150. }
  7151. }
  7152. const rawEl = document.getElementById('tools-mtr-raw');
  7153. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  7154. showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
  7155. } catch (err) {
  7156. showToast('MTR Error', err.message, 'error');
  7157. } finally {
  7158. if (btn) btn.disabled = false;
  7159. if (spinner) spinner.classList.add('hidden');
  7160. }
  7161. }
  7162. async function executeDNS(e) {
  7163. if (e) e.preventDefault();
  7164. const domain = document.getElementById('tools-dns-domain')?.value?.trim();
  7165. const type = document.getElementById('tools-dns-type')?.value || 'A';
  7166. const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
  7167. if (!domain) {
  7168. showToast('Input Required', 'Please enter a hostname or domain', 'warning');
  7169. return;
  7170. }
  7171. const btn = document.getElementById('tools-dns-btn');
  7172. const spinner = document.getElementById('tools-dns-spinner');
  7173. if (btn) btn.disabled = true;
  7174. if (spinner) spinner.classList.remove('hidden');
  7175. try {
  7176. const res = await fetch(`${API_BASE}/tools/dns`, {
  7177. method: 'POST',
  7178. headers: { 'Content-Type': 'application/json' },
  7179. body: JSON.stringify({ domain, type, server })
  7180. });
  7181. const data = await res.json();
  7182. if (!res.ok) {
  7183. showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
  7184. return;
  7185. }
  7186. const resCard = document.getElementById('tools-dns-results');
  7187. if (resCard) resCard.classList.remove('hidden');
  7188. const metaEl = document.getElementById('tools-dns-meta');
  7189. if (metaEl) metaEl.innerText = `Resolved in ${data.query_time_ms ?? 0} ms via ${escapeHtml(data.server || 'System DNS')}`;
  7190. const tbody = document.getElementById('tools-dns-tbody');
  7191. if (tbody) {
  7192. if (Array.isArray(data.records) && data.records.length > 0) {
  7193. tbody.innerHTML = data.records.map(r => `
  7194. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  7195. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.name)}</td>
  7196. <td class="py-2.5 px-3 text-slate-400">${r.ttl}s</td>
  7197. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.class || 'IN')}</td>
  7198. <td class="py-2.5 px-3"><span class="px-2 py-0.5 rounded text-[10px] font-bold bg-cyan-950 text-cyan-300 border border-cyan-800/60">${escapeHtml(r.type)}</span></td>
  7199. <td class="py-2.5 px-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
  7200. </tr>
  7201. `).join('');
  7202. } else {
  7203. tbody.innerHTML = `<tr><td colspan="5" class="p-4 text-center text-xs text-amber-400 font-mono">No answer records returned for ${escapeHtml(type)} query</td></tr>`;
  7204. }
  7205. }
  7206. const rawEl = document.getElementById('tools-dns-raw');
  7207. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  7208. showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
  7209. } catch (err) {
  7210. showToast('DNS Error', err.message, 'error');
  7211. } finally {
  7212. if (btn) btn.disabled = false;
  7213. if (spinner) spinner.classList.add('hidden');
  7214. }
  7215. }
  7216. async function executePortProbe(e) {
  7217. if (e) e.preventDefault();
  7218. const target = document.getElementById('tools-port-target')?.value?.trim();
  7219. const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
  7220. const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
  7221. if (!target || !port) {
  7222. showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
  7223. return;
  7224. }
  7225. const btn = document.getElementById('tools-port-btn');
  7226. const spinner = document.getElementById('tools-port-spinner');
  7227. if (btn) btn.disabled = true;
  7228. if (spinner) spinner.classList.remove('hidden');
  7229. try {
  7230. const res = await fetch(`${API_BASE}/tools/port-probe`, {
  7231. method: 'POST',
  7232. headers: { 'Content-Type': 'application/json' },
  7233. body: JSON.stringify({ target, port, timeout })
  7234. });
  7235. const data = await res.json();
  7236. if (!res.ok) {
  7237. showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
  7238. return;
  7239. }
  7240. const resCard = document.getElementById('tools-port-results');
  7241. if (resCard) resCard.classList.remove('hidden');
  7242. const banner = document.getElementById('tools-port-banner');
  7243. const icon = document.getElementById('tools-port-icon');
  7244. const title = document.getElementById('tools-port-title');
  7245. const sub = document.getElementById('tools-port-sub');
  7246. const latency = document.getElementById('tools-port-latency');
  7247. if (data.open) {
  7248. if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
  7249. if (icon) {
  7250. icon.className = 'w-8 h-8 rounded-full flex items-center justify-center font-bold text-sm bg-emerald-500/20 text-emerald-400 border border-emerald-500/40';
  7251. icon.innerText = '✓';
  7252. }
  7253. if (title) {
  7254. title.className = 'text-sm font-bold text-emerald-300';
  7255. title.innerText = `PORT ${port} OPEN / LISTENING`;
  7256. }
  7257. if (sub) {
  7258. sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
  7259. sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
  7260. }
  7261. if (latency) {
  7262. latency.className = 'text-base font-bold font-mono text-emerald-300';
  7263. latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
  7264. }
  7265. } else {
  7266. if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-800/50 flex items-center justify-between';
  7267. if (icon) {
  7268. icon.className = 'w-8 h-8 rounded-full flex items-center justify-center font-bold text-sm bg-rose-500/20 text-rose-400 border border-rose-500/40';
  7269. icon.innerText = '✕';
  7270. }
  7271. if (title) {
  7272. title.className = 'text-sm font-bold text-rose-300';
  7273. title.innerText = `PORT ${port} CLOSED / FILTERED`;
  7274. }
  7275. if (sub) {
  7276. sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
  7277. sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
  7278. }
  7279. if (latency) {
  7280. latency.className = 'text-base font-bold font-mono text-slate-500';
  7281. latency.innerText = '--';
  7282. }
  7283. }
  7284. const rawEl = document.getElementById('tools-port-raw');
  7285. if (rawEl) rawEl.innerText = data.raw_output || (data.open ? `Successfully connected to ${target}:${port} in ${data.latency_ms} ms` : `Connection failed: ${data.error || 'timed out or connection refused'}`);
  7286. showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
  7287. } catch (err) {
  7288. showToast('Probe Error', err.message, 'error');
  7289. } finally {
  7290. if (btn) btn.disabled = false;
  7291. if (spinner) spinner.classList.add('hidden');
  7292. }
  7293. }
  7294. // ==========================================
  7295. // DHCP CLIENT (/ip dhcp-client) CONTROLLER
  7296. // ==========================================
  7297. async function loadDHCPClients(showToastMsg = false) {
  7298. try {
  7299. const [clientsRes, sumRes] = await Promise.all([
  7300. fetch(`${API_BASE}/dhcp/clients`),
  7301. fetch(`${API_BASE}/dhcp/clients/summary`)
  7302. ]);
  7303. if (clientsRes.ok) {
  7304. state.dhcpClients = await clientsRes.json();
  7305. }
  7306. if (sumRes.ok) {
  7307. state.dhcpSummary = await sumRes.json();
  7308. }
  7309. renderDHCPClients();
  7310. updateDHCPSummaryCards();
  7311. const bDhcp = document.getElementById('badge-dhcp-client-count');
  7312. if (bDhcp && state.dhcpSummary) {
  7313. bDhcp.innerText = state.dhcpSummary.total_clients || 0;
  7314. }
  7315. if (showToastMsg) {
  7316. showToast('Refreshed', 'DHCP Client telemetry updated', 'info');
  7317. }
  7318. } catch (err) {
  7319. console.error('Failed to load DHCP clients:', err);
  7320. if (showToastMsg) {
  7321. showToast('Notice', 'Unable to fetch DHCP client status', 'warning');
  7322. }
  7323. }
  7324. }
  7325. function updateDHCPSummaryCards() {
  7326. const sum = state.dhcpSummary || {
  7327. total_clients: (state.dhcpClients || []).length,
  7328. bound_clients: (state.dhcpClients || []).filter(c => c.status === 'bound').length,
  7329. searching_clients: (state.dhcpClients || []).filter(c => c.status === 'searching').length,
  7330. disabled_clients: (state.dhcpClients || []).filter(c => !c.enabled).length
  7331. };
  7332. const totalEl = document.getElementById('dhcp-stat-total');
  7333. const boundEl = document.getElementById('dhcp-stat-bound');
  7334. const searchEl = document.getElementById('dhcp-stat-searching');
  7335. const disEl = document.getElementById('dhcp-stat-disabled');
  7336. if (totalEl) totalEl.innerText = sum.total_clients ?? 0;
  7337. if (boundEl) boundEl.innerText = sum.bound_clients ?? 0;
  7338. if (searchEl) searchEl.innerText = sum.searching_clients ?? 0;
  7339. if (disEl) disEl.innerText = sum.disabled_clients ?? 0;
  7340. }
  7341. function renderDHCPClients() {
  7342. const tbody = document.getElementById('dhcp-clients-tbody');
  7343. const emptyState = document.getElementById('dhcp-clients-empty');
  7344. if (!tbody) return;
  7345. const clients = Array.isArray(state.dhcpClients) ? state.dhcpClients : [];
  7346. if (clients.length === 0) {
  7347. tbody.innerHTML = '';
  7348. if (emptyState) emptyState.classList.remove('hidden');
  7349. return;
  7350. }
  7351. if (emptyState) emptyState.classList.add('hidden');
  7352. tbody.innerHTML = clients.map(c => {
  7353. let statusBadge = '';
  7354. if (!c.enabled) {
  7355. statusBadge = '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">DISABLED</span>';
  7356. } else if (c.status === 'bound') {
  7357. statusBadge = '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-emerald-950 text-emerald-300 border border-emerald-800/60 inline-flex items-center gap-1.5"><span class="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></span>BOUND</span>';
  7358. } else if (c.status === 'searching') {
  7359. statusBadge = '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-amber-950 text-amber-300 border border-amber-800/60 inline-flex items-center gap-1.5"><span class="w-1.5 h-1.5 rounded-full bg-amber-400 animate-ping"></span>SEARCHING...</span>';
  7360. } else if (c.status === 'stopped') {
  7361. statusBadge = '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">STOPPED</span>';
  7362. } else {
  7363. statusBadge = `<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-rose-950 text-rose-300 border border-rose-800/60">${escapeHtml((c.status || 'UNKNOWN').toUpperCase())}</span>`;
  7364. }
  7365. const ipDisplay = c.ip_address ? `<span class="font-bold text-white">${escapeHtml(c.ip_address)}</span>` : '<span class="text-slate-500 italic">No lease</span>';
  7366. const gwDisplay = c.gateway ? `<span class="text-slate-300">${escapeHtml(c.gateway)}</span>` : '<span class="text-slate-600">--</span>';
  7367. const srvDisplay = c.dhcp_server ? `<span class="text-slate-300">${escapeHtml(c.dhcp_server)}</span>` : '<span class="text-slate-600">--</span>';
  7368. const dnsDisplay = (Array.isArray(c.dns_servers) && c.dns_servers.length > 0) ? `<span class="text-cyan-400">${c.dns_servers.map(d => escapeHtml(d)).join(', ')}</span>` : '<span class="text-slate-600">--</span>';
  7369. const expDisplay = c.expires_in ? `<span class="text-purple-300">${escapeHtml(c.expires_in)}</span>` : '<span class="text-slate-600">--</span>';
  7370. // Option flags
  7371. const flags = [];
  7372. if (c.add_default_route) flags.push('<span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 border border-slate-700" title="Add Default Route">+GW</span>');
  7373. if (c.use_peer_dns) flags.push('<span class="px-1.5 py-0.5 rounded text-[10px] bg-cyan-950/60 text-cyan-300 border border-cyan-800/50" title="Use Peer DNS">+DNS</span>');
  7374. if (c.use_peer_ntp) flags.push('<span class="px-1.5 py-0.5 rounded text-[10px] bg-indigo-950/60 text-indigo-300 border border-indigo-800/50" title="Use Peer NTP">+NTP</span>');
  7375. flags.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800/60 text-slate-400" title="Default Route Distance">dist:${c.default_route_distance || 1}</span>`);
  7376. return `
  7377. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 text-xs transition">
  7378. <td class="py-3 px-4">
  7379. <div class="flex items-center gap-2">
  7380. <span class="font-bold text-white text-sm">${escapeHtml(c.interface)}</span>
  7381. ${c.comment ? `<span class="text-[11px] text-slate-400 font-sans italic">(${escapeHtml(c.comment)})</span>` : ''}
  7382. </div>
  7383. </td>
  7384. <td class="py-3 px-4">${statusBadge}</td>
  7385. <td class="py-3 px-4 font-mono">${ipDisplay}</td>
  7386. <td class="py-3 px-4 font-mono">${gwDisplay}</td>
  7387. <td class="py-3 px-4 font-mono">${srvDisplay}</td>
  7388. <td class="py-3 px-4 font-mono text-[11px]">${dnsDisplay}</td>
  7389. <td class="py-3 px-4 font-mono text-[11px]">${expDisplay}</td>
  7390. <td class="py-3 px-4">
  7391. <div class="flex flex-wrap gap-1 font-mono">${flags.join('')}</div>
  7392. </td>
  7393. <td class="py-3 px-4 text-right space-x-1.5 font-sans whitespace-nowrap">
  7394. ${c.enabled ? `
  7395. <button onclick="renewDHCPClient('${c.id}')" class="px-2 py-1 rounded bg-slate-800 hover:bg-slate-700 text-amber-400 text-xs font-medium border border-slate-700 transition" title="Renew Lease">Renew</button>
  7396. <button onclick="releaseDHCPClient('${c.id}')" class="px-2 py-1 rounded bg-slate-800 hover:bg-slate-700 text-slate-300 text-xs font-medium border border-slate-700 transition" title="Release Lease">Release</button>
  7397. <button onclick="toggleDHCPClientState('${c.id}', false)" class="px-2 py-1 rounded bg-amber-500/10 hover:bg-amber-500/20 text-amber-400 text-xs font-medium border border-amber-500/30 transition" title="Disable DHCP Client">Disable</button>
  7398. ` : `
  7399. <button onclick="toggleDHCPClientState('${c.id}', true)" class="px-2.5 py-1 rounded bg-emerald-500/10 hover:bg-emerald-500/20 text-emerald-400 text-xs font-semibold border border-emerald-500/30 transition" title="Enable DHCP Client">Enable</button>
  7400. `}
  7401. <button onclick="openDHCPClientModal('${c.id}')" class="px-2 py-1 rounded bg-slate-800 hover:bg-slate-700 text-white text-xs font-medium border border-slate-700 transition" title="Edit Settings">Edit</button>
  7402. <button onclick="deleteDHCPClient('${c.id}', '${c.interface}')" class="px-2 py-1 rounded bg-rose-500/10 hover:bg-rose-500/20 text-rose-400 text-xs font-medium border border-rose-500/30 transition" title="Remove Client">✕</button>
  7403. </td>
  7404. </tr>
  7405. `;
  7406. }).join('');
  7407. }
  7408. function openDHCPClientModal(clientId = null) {
  7409. const modal = document.getElementById('modal-dhcp-client');
  7410. if (!modal) return;
  7411. const title = document.getElementById('modal-dhcp-title');
  7412. const idInput = document.getElementById('modal-dhcp-id');
  7413. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  7414. const distInput = document.getElementById('modal-dhcp-distance');
  7415. const commentInput = document.getElementById('modal-dhcp-comment');
  7416. const defRouteCheck = document.getElementById('modal-dhcp-def-route');
  7417. const peerDnsCheck = document.getElementById('modal-dhcp-peer-dns');
  7418. const peerNtpCheck = document.getElementById('modal-dhcp-peer-ntp');
  7419. const enabledCheck = document.getElementById('modal-dhcp-enabled');
  7420. // Populate interfaces
  7421. if (ifaceSelect) {
  7422. let opts = '<option value="">Select interface...</option>';
  7423. const allIfaces = state.interfaces || [];
  7424. const allVlans = state.vlans || [];
  7425. const usedIfaces = new Set((state.dhcpClients || []).map(c => c.interface));
  7426. // Group 1: Physical & Bridge Interfaces
  7427. opts += '<optgroup label="Physical & Bridge Interfaces">';
  7428. allIfaces.forEach(i => {
  7429. const isConfigured = usedIfaces.has(i.name) ? ' (Configured)' : '';
  7430. opts += `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} [${escapeHtml(i.role || i.type)}]${isConfigured}</option>`;
  7431. });
  7432. opts += '</optgroup>';
  7433. // Group 2: VLAN Interfaces
  7434. if (allVlans.length > 0) {
  7435. opts += '<optgroup label="802.1Q VLAN Sub-interfaces">';
  7436. allVlans.forEach(v => {
  7437. const isConfigured = usedIfaces.has(v.name) ? ' (Configured)' : '';
  7438. opts += `<option value="${escapeHtml(v.name)}">${escapeHtml(v.name)} (VLAN ${v.vlan_id})${isConfigured}</option>`;
  7439. });
  7440. opts += '</optgroup>';
  7441. }
  7442. ifaceSelect.innerHTML = opts;
  7443. }
  7444. if (clientId) {
  7445. const client = (state.dhcpClients || []).find(c => c.id === clientId);
  7446. if (client) {
  7447. if (title) title.innerText = `Edit DHCP Client: ${client.interface}`;
  7448. if (idInput) idInput.value = client.id;
  7449. if (ifaceSelect) {
  7450. ifaceSelect.value = client.interface;
  7451. ifaceSelect.disabled = true; // interface cannot be changed on edit
  7452. }
  7453. if (distInput) distInput.value = client.default_route_distance || 1;
  7454. if (commentInput) commentInput.value = client.comment || '';
  7455. if (defRouteCheck) defRouteCheck.checked = client.add_default_route !== false;
  7456. if (peerDnsCheck) peerDnsCheck.checked = client.use_peer_dns !== false;
  7457. if (peerNtpCheck) peerNtpCheck.checked = client.use_peer_ntp !== false;
  7458. if (enabledCheck) enabledCheck.checked = client.enabled !== false;
  7459. }
  7460. } else {
  7461. if (title) title.innerText = 'Add DHCP Client';
  7462. if (idInput) idInput.value = '';
  7463. if (ifaceSelect) {
  7464. ifaceSelect.value = '';
  7465. ifaceSelect.disabled = false;
  7466. }
  7467. if (distInput) distInput.value = 1;
  7468. if (commentInput) commentInput.value = '';
  7469. if (defRouteCheck) defRouteCheck.checked = true;
  7470. if (peerDnsCheck) peerDnsCheck.checked = true;
  7471. if (peerNtpCheck) peerNtpCheck.checked = true;
  7472. if (enabledCheck) enabledCheck.checked = true;
  7473. }
  7474. modal.classList.remove('hidden');
  7475. }
  7476. function openDHCPClientModalForIface(ifaceName) {
  7477. openDHCPClientModal();
  7478. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  7479. if (ifaceSelect && ifaceName) {
  7480. ifaceSelect.value = ifaceName;
  7481. }
  7482. }
  7483. function closeDHCPClientModal() {
  7484. const modal = document.getElementById('modal-dhcp-client');
  7485. if (modal) modal.classList.add('hidden');
  7486. }
  7487. async function submitSaveDHCPClient(e) {
  7488. if (e) e.preventDefault();
  7489. const id = document.getElementById('modal-dhcp-id')?.value;
  7490. const iface = document.getElementById('modal-dhcp-iface')?.value?.trim();
  7491. const distance = parseInt(document.getElementById('modal-dhcp-distance')?.value || '1', 10);
  7492. const comment = document.getElementById('modal-dhcp-comment')?.value?.trim() || '';
  7493. const defRoute = document.getElementById('modal-dhcp-def-route')?.checked ?? true;
  7494. const peerDns = document.getElementById('modal-dhcp-peer-dns')?.checked ?? true;
  7495. const peerNtp = document.getElementById('modal-dhcp-peer-ntp')?.checked ?? true;
  7496. const enabled = document.getElementById('modal-dhcp-enabled')?.checked ?? true;
  7497. if (!id && !iface) {
  7498. showToast('Input Required', 'Please select an interface for the DHCP client', 'warning');
  7499. return;
  7500. }
  7501. try {
  7502. let res;
  7503. if (id) {
  7504. // PUT update
  7505. res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  7506. method: 'PUT',
  7507. headers: { 'Content-Type': 'application/json' },
  7508. body: JSON.stringify({
  7509. enabled,
  7510. add_default_route: defRoute,
  7511. default_route_distance: distance,
  7512. use_peer_dns: peerDns,
  7513. use_peer_ntp: peerNtp,
  7514. comment
  7515. })
  7516. });
  7517. } else {
  7518. // POST create
  7519. res = await fetch(`${API_BASE}/dhcp/clients`, {
  7520. method: 'POST',
  7521. headers: { 'Content-Type': 'application/json' },
  7522. body: JSON.stringify({
  7523. interface: iface,
  7524. enabled,
  7525. add_default_route: defRoute,
  7526. default_route_distance: distance,
  7527. use_peer_dns: peerDns,
  7528. use_peer_ntp: peerNtp,
  7529. comment
  7530. })
  7531. });
  7532. }
  7533. const data = await res.json();
  7534. if (!res.ok) {
  7535. showToast('Error', data.error || 'Failed to save DHCP client', 'error');
  7536. return;
  7537. }
  7538. closeDHCPClientModal();
  7539. showToast('Success', id ? 'DHCP Client updated successfully' : `DHCP Client activated on ${iface}`, 'success');
  7540. await loadDHCPClients();
  7541. fetchData(); // refresh interfaces list with new lease/status
  7542. } catch (err) {
  7543. showToast('Error', err.message, 'error');
  7544. }
  7545. }
  7546. async function toggleDHCPClientState(id, enabled) {
  7547. try {
  7548. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/state`, {
  7549. method: 'POST',
  7550. headers: { 'Content-Type': 'application/json' },
  7551. body: JSON.stringify({ enabled })
  7552. });
  7553. const data = await res.json();
  7554. if (!res.ok) {
  7555. showToast('Error', data.error || 'Failed to toggle client state', 'error');
  7556. return;
  7557. }
  7558. showToast('Updated', `DHCP client ${enabled ? 'enabled' : 'disabled'}`, 'info');
  7559. await loadDHCPClients();
  7560. fetchData();
  7561. } catch (err) {
  7562. showToast('Error', err.message, 'error');
  7563. }
  7564. }
  7565. async function renewDHCPClient(id) {
  7566. try {
  7567. showToast('Renewing...', 'Requesting DHCP lease renewal from upstream server', 'info');
  7568. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/renew`, {
  7569. method: 'POST'
  7570. });
  7571. const data = await res.json();
  7572. if (!res.ok) {
  7573. showToast('Error', data.error || 'Failed to renew lease', 'error');
  7574. return;
  7575. }
  7576. showToast('Lease Renewed', 'DHCP renewal signal sent successfully', 'success');
  7577. setTimeout(() => {
  7578. loadDHCPClients();
  7579. fetchData();
  7580. }, 1500);
  7581. } catch (err) {
  7582. showToast('Error', err.message, 'error');
  7583. }
  7584. }
  7585. async function releaseDHCPClient(id) {
  7586. try {
  7587. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/release`, {
  7588. method: 'POST'
  7589. });
  7590. const data = await res.json();
  7591. if (!res.ok) {
  7592. showToast('Error', data.error || 'Failed to release lease', 'error');
  7593. return;
  7594. }
  7595. showToast('Lease Released', 'DHCP lease released from upstream server', 'info');
  7596. await loadDHCPClients();
  7597. fetchData();
  7598. } catch (err) {
  7599. showToast('Error', err.message, 'error');
  7600. }
  7601. }
  7602. async function deleteDHCPClient(id, ifaceName) {
  7603. if (!confirm(`Are you sure you want to remove the DHCP Client on ${ifaceName}? The interface will release its dynamic IP.`)) {
  7604. return;
  7605. }
  7606. try {
  7607. const res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  7608. method: 'DELETE'
  7609. });
  7610. const data = await res.json();
  7611. if (!res.ok) {
  7612. showToast('Error', data.error || 'Failed to delete DHCP client', 'error');
  7613. return;
  7614. }
  7615. showToast('Deleted', `DHCP client removed from ${ifaceName}`, 'info');
  7616. await loadDHCPClients();
  7617. fetchData();
  7618. } catch (err) {
  7619. showToast('Error', err.message, 'error');
  7620. }
  7621. }