app.js 357 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438
  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. ifaceTbody.innerHTML = '';
  457. (state.interfaces || []).slice(0, 6).forEach(i => {
  458. const isUp = i.state === 'UP';
  459. const tr = document.createElement('tr');
  460. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  461. tr.onclick = () => openIfaceModal(i.name);
  462. tr.innerHTML = `
  463. <td class="py-2.5 font-bold text-white flex items-center gap-2">
  464. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  465. <span>${i.name}</span>
  466. </td>
  467. <td class="py-2.5 text-slate-300 font-sans"><span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300">${i.role || 'LAN'}</span></td>
  468. <td class="py-2.5 text-slate-300">${i.ipv4 && i.ipv4.length > 0 ? i.ipv4[0] : '<span class="text-slate-600">-</span>'}</td>
  469. <td class="py-2.5 text-right font-sans font-semibold ${isUp ? 'text-emerald-400' : 'text-rose-400'}">${i.state}</td>
  470. `;
  471. ifaceTbody.appendChild(tr);
  472. });
  473. const vlanTbody = document.getElementById('quick-vlans-table');
  474. vlanTbody.innerHTML = '';
  475. const vlans = state.vlans || [];
  476. if (vlans.length === 0) {
  477. vlanTbody.innerHTML = `<tr><td colspan="4" class="py-4 text-center text-slate-500 font-sans">No VLANs configured. Click "+ Add" above to create one.</td></tr>`;
  478. } else {
  479. vlans.slice(0, 6).forEach(v => {
  480. const tr = document.createElement('tr');
  481. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  482. tr.onclick = () => openIfaceModal(v.name);
  483. tr.innerHTML = `
  484. <td class="py-2.5"><span class="px-2 py-0.5 rounded text-[11px] bg-cyan-950 text-cyan-400 border border-cyan-800 font-bold">VLAN ${v.vlan_id}</span></td>
  485. <td class="py-2.5 text-white font-bold">${v.name}</td>
  486. <td class="py-2.5 text-slate-300">${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600">Unnumbered</span>'}</td>
  487. <td class="py-2.5 text-right text-slate-400">${v.parent_name || 'eth0'}</td>
  488. `;
  489. vlanTbody.appendChild(tr);
  490. });
  491. }
  492. }
  493. // Expand / Collapse Handlers
  494. function toggleExpand(parentName) {
  495. if (state.expandedParents.has(parentName)) {
  496. state.expandedParents.delete(parentName);
  497. } else {
  498. state.expandedParents.add(parentName);
  499. }
  500. renderInterfacesList();
  501. }
  502. function expandAllIfaces(expand) {
  503. if (expand) {
  504. (state.interfaces || []).forEach(i => {
  505. if (!i.is_vlan) state.expandedParents.add(i.name);
  506. });
  507. } else {
  508. state.expandedParents.clear();
  509. }
  510. renderInterfacesList();
  511. }
  512. // Filter and Render Hierarchical Interfaces List
  513. function filterIfaces(filter) {
  514. state.ifaceFilter = filter;
  515. document.querySelectorAll('.filter-btn').forEach(btn => {
  516. 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';
  517. });
  518. const activeBtn = document.getElementById(`filter-${filter}`);
  519. if (activeBtn) {
  520. activeBtn.className = 'filter-btn px-3 py-1.5 rounded-lg text-xs font-medium bg-slate-800 text-white border border-slate-700';
  521. }
  522. renderInterfacesList();
  523. }
  524. function renderInterfacesList() {
  525. const tbody = document.getElementById('interfaces-tree-tbody');
  526. const emptyState = document.getElementById('interfaces-empty-state');
  527. const summary = document.getElementById('ifaces-list-summary');
  528. const query = (document.getElementById('iface-search')?.value || '').toLowerCase();
  529. tbody.innerHTML = '';
  530. const allIfaces = state.interfaces || [];
  531. const allVlans = state.vlans || [];
  532. const parentIfaces = allIfaces.filter(i => !i.is_vlan);
  533. const filteredParents = parentIfaces.filter(parent => {
  534. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  535. if (query) {
  536. const matchParent = parent.name.toLowerCase().includes(query) || (parent.role || '').toLowerCase().includes(query);
  537. const matchVlan = childVlans.some(v => v.name.toLowerCase().includes(query) || String(v.vlan_id).includes(query) || (v.description || '').toLowerCase().includes(query));
  538. if (!matchParent && !matchVlan) return false;
  539. }
  540. if (state.ifaceFilter === 'has_vlans') return childVlans.length > 0;
  541. if (state.ifaceFilter === 'physical') return parent.type !== 'loopback';
  542. if (state.ifaceFilter === 'up') return parent.state === 'UP';
  543. return true;
  544. });
  545. if (summary) {
  546. summary.innerText = `${parentIfaces.length} Physical/Parent Links • ${allVlans.length} Active VLANs`;
  547. }
  548. if (filteredParents.length === 0) {
  549. emptyState?.classList.remove('hidden');
  550. return;
  551. }
  552. emptyState?.classList.add('hidden');
  553. filteredParents.forEach(parent => {
  554. const isUp = parent.state === 'UP';
  555. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  556. const isExpanded = state.expandedParents.has(parent.name);
  557. const parentRow = document.createElement('tr');
  558. parentRow.className = `hover:bg-slate-800/50 transition border-b border-slate-800/80 ${isExpanded ? 'bg-slate-900/80' : ''}`;
  559. parentRow.innerHTML = `
  560. <td class="py-3 px-3 text-center">
  561. <button onclick="toggleExpand('${parent.name}')" title="${isExpanded ? 'Collapse VLANs' : 'Expand VLANs'}"
  562. class="w-6 h-6 rounded flex items-center justify-center hover:bg-slate-800 text-slate-400 hover:text-white transition">
  563. <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">
  564. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M9 5l7 7-7 7" />
  565. </svg>
  566. </button>
  567. </td>
  568. <td class="py-3 px-4">
  569. <div class="flex items-center space-x-2.5">
  570. <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">
  571. ${parent.type === 'loopback' ? 'LO' : 'NIC'}
  572. </div>
  573. <div>
  574. <div class="flex items-center gap-2">
  575. <span class="font-bold text-white text-sm cursor-pointer hover:text-cyan-400" onclick="toggleExpand('${parent.name}')">${parent.name}</span>
  576. ${childVlans.length > 0
  577. ? `<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>`
  578. : `<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>`
  579. }
  580. </div>
  581. <div class="text-[10px] text-slate-500 font-sans mt-0.5">${parent.type}</div>
  582. </div>
  583. </div>
  584. </td>
  585. <td class="py-3 px-4 font-sans">
  586. <div class="flex items-center gap-1.5">
  587. <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>
  588. <span class="text-xs text-slate-400 truncate max-w-[120px]">${parent.description || '-'}</span>
  589. </div>
  590. </td>
  591. <td class="py-3 px-4">
  592. ${parent.ipv4 && parent.ipv4.length > 0
  593. ? `<div class="text-white font-medium">${parent.ipv4[0]}</div>`
  594. : '<span class="text-slate-600 font-sans">Unassigned</span>'
  595. }
  596. ${(() => {
  597. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  598. if (!c) return '';
  599. 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');
  600. 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>`;
  601. })()}
  602. </td>
  603. <td class="py-3 px-4 text-slate-400 text-[11px]">
  604. <div>${parent.mac || 'N/A'}</div>
  605. <div class="text-[10px] text-slate-500">MTU ${parent.mtu}</div>
  606. </td>
  607. <td class="py-3 px-4 text-[11px]">
  608. <div class="flex items-center space-x-2">
  609. <span class="text-emerald-400">↓ ${parent.rate?.rx_human || '0 B/s'}</span>
  610. <span class="text-cyan-400">↑ ${parent.rate?.tx_human || '0 B/s'}</span>
  611. </div>
  612. </td>
  613. <td class="py-3 px-4 font-sans">
  614. <button onclick="toggleInterfaceState('${parent.name}', '${isUp ? 'down' : 'up'}')"
  615. class="flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full transition ${
  616. 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'
  617. }" title="Click to toggle link status">
  618. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  619. <span>${parent.state}</span>
  620. </button>
  621. </td>
  622. <td class="py-3 px-4 text-right space-x-2 font-sans">
  623. ${(() => {
  624. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  625. if (c) {
  626. 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>`;
  627. }
  628. 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>`;
  629. })()}
  630. <button onclick="openVlanModal('${parent.name}')"
  631. 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">
  632. + Add VLAN
  633. </button>
  634. <button onclick="openIfaceModal('${parent.name}')"
  635. 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">
  636. Configure
  637. </button>
  638. </td>
  639. `;
  640. tbody.appendChild(parentRow);
  641. if (isExpanded) {
  642. const drawerRow = document.createElement('tr');
  643. drawerRow.className = 'bg-slate-950/80 border-b border-slate-800/90';
  644. const drawerCell = document.createElement('td');
  645. drawerCell.colSpan = 8;
  646. drawerCell.className = 'p-0';
  647. drawerCell.innerHTML = `
  648. <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">
  649. <div class="flex items-center justify-between mb-3">
  650. <div class="flex items-center space-x-3">
  651. <span class="font-bold text-xs text-white uppercase tracking-wider flex items-center gap-1.5 font-sans">
  652. <span>VLAN Sub-interfaces on <code class="text-cyan-300 lowercase">${parent.name}</code></span>
  653. </span>
  654. <span class="text-[11px] bg-cyan-950 text-cyan-400 px-2 py-0.5 rounded-full border border-cyan-800/60 font-mono">
  655. ${childVlans.length} Attached
  656. </span>
  657. </div>
  658. <button onclick="openVlanModal('${parent.name}')"
  659. 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">
  660. <span>+ Create VLAN on ${parent.name}</span>
  661. </button>
  662. </div>
  663. ${childVlans.length === 0 ? `
  664. <div class="p-6 text-center border border-dashed border-slate-800 rounded-xl bg-slate-900/40 font-sans">
  665. <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>
  666. <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">
  667. <span>+ Create Your First VLAN on ${parent.name}</span>
  668. </button>
  669. </div>
  670. ` : `
  671. <div class="overflow-x-auto rounded-lg border border-slate-800 bg-slate-900/90 shadow-inner">
  672. <table class="w-full text-left text-xs font-mono">
  673. <thead class="text-slate-400 bg-slate-950/70 border-b border-slate-800 uppercase tracking-wider text-[10px] font-sans">
  674. <tr>
  675. <th class="py-2.5 px-4">VLAN ID</th>
  676. <th class="py-2.5 px-4">Interface Device</th>
  677. <th class="py-2.5 px-4">Subnet Gateway</th>
  678. <th class="py-2.5 px-4">Role / Alias</th>
  679. <th class="py-2.5 px-4">MTU</th>
  680. <th class="py-2.5 px-4">Throughput</th>
  681. <th class="py-2.5 px-4">Status</th>
  682. <th class="py-2.5 px-4 text-right">Actions</th>
  683. </tr>
  684. </thead>
  685. <tbody class="divide-y divide-slate-800/70">
  686. ${childVlans.map(v => {
  687. const isVlanUp = v.state === 'UP';
  688. return `
  689. <tr class="hover:bg-slate-800/40 transition">
  690. <td class="py-2.5 px-4">
  691. <span class="px-2 py-0.5 rounded text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800 shadow-sm">
  692. VLAN ${v.vlan_id}
  693. </span>
  694. </td>
  695. <td class="py-2.5 px-4 font-bold text-white flex items-center gap-1.5">
  696. <span class="text-cyan-500">└─</span>
  697. <span>${v.name}</span>
  698. </td>
  699. <td class="py-2.5 px-4 text-emerald-400 font-medium">
  700. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  701. ${(() => {
  702. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  703. if (!c) return '';
  704. 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';
  705. 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>`;
  706. })()}
  707. </td>
  708. <td class="py-2.5 px-4 font-sans text-slate-300">
  709. <span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 mr-1.5">${v.role || 'VLAN'}</span>
  710. <span class="text-slate-400 text-xs">${v.description || '-'}</span>
  711. </td>
  712. <td class="py-2.5 px-4 text-slate-400">${v.mtu}</td>
  713. <td class="py-2.5 px-4 text-[11px]">
  714. <span class="text-emerald-400">↓ ${v.rate?.rx_human || '0 B/s'}</span>
  715. <span class="text-cyan-400 ml-1.5">↑ ${v.rate?.tx_human || '0 B/s'}</span>
  716. </td>
  717. <td class="py-2.5 px-4 font-sans">
  718. <button onclick="toggleInterfaceState('${v.name}', '${isVlanUp ? 'down' : 'up'}')"
  719. class="flex items-center gap-1 text-[11px] font-semibold px-2 py-0.5 rounded-full ${
  720. 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'
  721. }">
  722. <span class="w-1.5 h-1.5 rounded-full ${isVlanUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  723. <span>${v.state}</span>
  724. </button>
  725. </td>
  726. <td class="py-2.5 px-4 text-right space-x-1.5 font-sans">
  727. ${(() => {
  728. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  729. if (c) {
  730. 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>`;
  731. }
  732. 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>`;
  733. })()}
  734. <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>
  735. <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>
  736. </td>
  737. </tr>
  738. `;
  739. }).join('')}
  740. </tbody>
  741. </table>
  742. </div>
  743. `}
  744. </div>
  745. `;
  746. drawerRow.appendChild(drawerCell);
  747. tbody.appendChild(drawerRow);
  748. }
  749. });
  750. }
  751. // Render VLANs Dedicated View
  752. function renderVlansList() {
  753. const tbody = document.getElementById('vlans-table-body');
  754. if (!tbody) return;
  755. const emptyState = document.getElementById('vlans-empty-state');
  756. const countBadge = document.getElementById('vlans-table-count');
  757. const query = (document.getElementById('vlan-search')?.value || '').toLowerCase();
  758. tbody.innerHTML = '';
  759. const allVlans = state.vlans || [];
  760. if (countBadge) countBadge.innerText = allVlans.length;
  761. const filtered = allVlans.filter(v => {
  762. if (!query) return true;
  763. return v.name.toLowerCase().includes(query) ||
  764. String(v.vlan_id).includes(query) ||
  765. (v.description || '').toLowerCase().includes(query) ||
  766. (v.ipv4 && v.ipv4.some(ip => ip.includes(query)));
  767. });
  768. if (allVlans.length === 0) {
  769. emptyState.classList.remove('hidden');
  770. return;
  771. }
  772. emptyState.classList.add('hidden');
  773. filtered.forEach(v => {
  774. const isUp = v.state === 'UP';
  775. const tr = document.createElement('tr');
  776. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  777. tr.innerHTML = `
  778. <td class="py-3 px-4">
  779. <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">
  780. VLAN ${v.vlan_id}
  781. </span>
  782. </td>
  783. <td class="py-3 px-4 font-bold text-white">${v.name}</td>
  784. <td class="py-3 px-4 text-slate-300">
  785. <span class="bg-slate-800 text-slate-200 px-2 py-0.5 rounded text-[11px]">${v.parent_name || 'eth0'}</span>
  786. </td>
  787. <td class="py-3 px-4 text-emerald-400 font-medium">
  788. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  789. </td>
  790. <td class="py-3 px-4 text-slate-300 font-sans">
  791. <span class="text-slate-400 text-xs">${v.description || v.role || '-'}</span>
  792. </td>
  793. <td class="py-3 px-4 text-slate-400">${v.mtu}</td>
  794. <td class="py-3 px-4 font-sans">
  795. <button onclick="toggleInterfaceState('${v.name}', '${isUp ? 'down' : 'up'}')"
  796. class="flex items-center gap-1.5 text-xs font-semibold px-2 py-0.5 rounded-full ${
  797. 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'
  798. }">
  799. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  800. <span>${v.state}</span>
  801. </button>
  802. </td>
  803. <td class="py-3 px-4 text-right space-x-2 font-sans">
  804. <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>
  805. <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>
  806. </td>
  807. `;
  808. tbody.appendChild(tr);
  809. });
  810. }
  811. // Toggle interface UP / DOWN
  812. async function toggleInterfaceState(name, newState) {
  813. try {
  814. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(name)}/state`, {
  815. method: 'POST',
  816. headers: { 'Content-Type': 'application/json' },
  817. body: JSON.stringify({ state: newState })
  818. });
  819. const data = await res.json();
  820. if (res.ok) {
  821. showToast('Interface Updated', `Interface ${name} is now ${newState.toUpperCase()}`, 'success');
  822. fetchData(false);
  823. } else {
  824. showToast('Error', data.message || 'Failed to toggle interface state', 'error');
  825. }
  826. } catch (err) {
  827. showToast('Error', err.message, 'error');
  828. }
  829. }
  830. // ---------------- MikroTik Flag & Utilities ----------------
  831. function renderMikroTikFlag(running, disabled) {
  832. if (running) {
  833. 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>`;
  834. }
  835. if (disabled) {
  836. 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>`;
  837. }
  838. 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>`;
  839. }
  840. function copyToClipboard(text, label = 'Text') {
  841. navigator.clipboard.writeText(text).then(() => {
  842. showToast('Copied', `${label} copied to clipboard`, 'success');
  843. }).catch(() => {
  844. prompt('Copy value:', text);
  845. });
  846. }
  847. // ======================== PPPoE Multi-Instance ========================
  848. async function loadPPPoE(populateInputs = true) {
  849. try {
  850. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`);
  851. const list = await res.json();
  852. state.pppoeList = Array.isArray(list) ? list : [];
  853. const badge = document.getElementById('pppoe-count-badge');
  854. if (badge) badge.innerText = `${state.pppoeList.length} Interface${state.pppoeList.length !== 1 ? 's' : ''}`;
  855. const tbody = document.getElementById('pppoe-table-body');
  856. const empty = document.getElementById('pppoe-empty');
  857. if (!tbody) return;
  858. tbody.innerHTML = '';
  859. if (state.pppoeList.length === 0) {
  860. if (empty) empty.classList.remove('hidden');
  861. } else {
  862. if (empty) empty.classList.add('hidden');
  863. state.pppoeList.forEach(inst => {
  864. const tr = document.createElement('tr');
  865. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  866. tr.innerHTML = `
  867. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  868. <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
  869. <td class="py-2.5 px-3 text-cyan-400 font-mono">${inst.interface}</td>
  870. <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
  871. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
  872. <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
  873. <td class="py-2.5 px-3 text-center">
  874. <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'}">
  875. ${inst.default_route ? 'Yes' : 'No'}
  876. </span>
  877. </td>
  878. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  879. ${inst.running ? `
  880. <button onclick="disconnectPPPoEInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  881. ` : `
  882. <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>
  883. `}
  884. <button onclick="togglePPPoEState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  885. ${inst.disabled ? 'Enable' : 'Disable'}
  886. </button>
  887. <button onclick="openEditPPPoEModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  888. <button onclick="deletePPPoEInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  889. </td>
  890. `;
  891. tbody.appendChild(tr);
  892. });
  893. }
  894. } catch (err) {
  895. console.error('Failed to load PPPoE:', err);
  896. }
  897. }
  898. function openAddPPPoEModal() {
  899. document.getElementById('pppoe-modal-title').innerText = 'Add PPPoE Client Interface';
  900. document.getElementById('pppoe-modal-edit-orig').value = '';
  901. document.getElementById('pppoe-modal-name').value = `pppoe-out${(state.pppoeList || []).length + 1}`;
  902. document.getElementById('pppoe-modal-name').readOnly = false;
  903. document.getElementById('pppoe-modal-user').value = '';
  904. document.getElementById('pppoe-modal-pass').value = '';
  905. document.getElementById('pppoe-modal-service').value = '';
  906. document.getElementById('pppoe-modal-mtu').value = '1492';
  907. document.getElementById('pppoe-modal-defroute').checked = true;
  908. document.getElementById('pppoe-modal-reconnect').checked = true;
  909. document.getElementById('pppoe-modal-disabled').checked = false;
  910. // Populate interfaces
  911. const sel = document.getElementById('pppoe-modal-iface');
  912. sel.innerHTML = '';
  913. (state.interfaces || []).forEach(i => {
  914. if (i.name === 'lo') return;
  915. const opt = document.createElement('option');
  916. opt.value = i.name;
  917. opt.innerText = `${i.name} (${i.role || i.type})`;
  918. sel.appendChild(opt);
  919. });
  920. document.getElementById('pppoe-modal').classList.remove('hidden');
  921. }
  922. function openEditPPPoEModal(name) {
  923. const inst = (state.pppoeList || []).find(i => i.name === name);
  924. if (!inst) return;
  925. document.getElementById('pppoe-modal-title').innerText = `Edit PPPoE Client: ${name}`;
  926. document.getElementById('pppoe-modal-edit-orig').value = name;
  927. document.getElementById('pppoe-modal-name').value = inst.name;
  928. document.getElementById('pppoe-modal-name').readOnly = true;
  929. document.getElementById('pppoe-modal-user').value = inst.username || '';
  930. document.getElementById('pppoe-modal-pass').value = inst.password || '';
  931. document.getElementById('pppoe-modal-service').value = inst.service_name || '';
  932. document.getElementById('pppoe-modal-mtu').value = inst.mtu || 1492;
  933. document.getElementById('pppoe-modal-defroute').checked = inst.default_route ?? true;
  934. document.getElementById('pppoe-modal-reconnect').checked = inst.auto_reconnect ?? true;
  935. document.getElementById('pppoe-modal-disabled').checked = !!inst.disabled;
  936. const sel = document.getElementById('pppoe-modal-iface');
  937. sel.innerHTML = '';
  938. (state.interfaces || []).forEach(i => {
  939. if (i.name === 'lo') return;
  940. const opt = document.createElement('option');
  941. opt.value = i.name;
  942. opt.innerText = `${i.name} (${i.role || i.type})`;
  943. if (i.name === inst.interface) opt.selected = true;
  944. sel.appendChild(opt);
  945. });
  946. document.getElementById('pppoe-modal').classList.remove('hidden');
  947. }
  948. function closePPPoEModal() {
  949. document.getElementById('pppoe-modal').classList.add('hidden');
  950. }
  951. async function submitSavePPPoE(e) {
  952. e.preventDefault();
  953. const name = document.getElementById('pppoe-modal-name').value.trim();
  954. const iface = document.getElementById('pppoe-modal-iface').value;
  955. const user = document.getElementById('pppoe-modal-user').value.trim();
  956. const pass = document.getElementById('pppoe-modal-pass').value;
  957. const service = document.getElementById('pppoe-modal-service').value.trim();
  958. const mtu = parseInt(document.getElementById('pppoe-modal-mtu').value, 10) || 1492;
  959. const defRoute = document.getElementById('pppoe-modal-defroute').checked;
  960. const reconnect = document.getElementById('pppoe-modal-reconnect').checked;
  961. const disabled = document.getElementById('pppoe-modal-disabled').checked;
  962. try {
  963. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`, {
  964. method: 'POST',
  965. headers: { 'Content-Type': 'application/json' },
  966. body: JSON.stringify({
  967. name,
  968. interface: iface,
  969. username: user,
  970. password: pass,
  971. service_name: service,
  972. mtu,
  973. default_route: defRoute,
  974. auto_reconnect: reconnect,
  975. disabled
  976. })
  977. });
  978. if (res.ok) {
  979. showToast('PPPoE Saved', `Configuration for ${name} saved`, 'success');
  980. closePPPoEModal();
  981. loadPPPoE(false);
  982. fetchData(false);
  983. } else {
  984. const err = await res.json();
  985. showToast('Error', err.message || 'Failed to save PPPoE', 'error');
  986. }
  987. } catch (err) {
  988. showToast('Error', err.message, 'error');
  989. }
  990. }
  991. async function connectPPPoEInstance(name) {
  992. try {
  993. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  994. if (res.ok) {
  995. showToast('Connecting', `Dialing ${name}...`, 'info');
  996. setTimeout(() => loadPPPoE(false), 2000);
  997. }
  998. } catch (err) {
  999. showToast('Error', err.message, 'error');
  1000. }
  1001. }
  1002. async function disconnectPPPoEInstance(name) {
  1003. try {
  1004. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1005. if (res.ok) {
  1006. showToast('Disconnected', `${name} session terminated`, 'info');
  1007. setTimeout(() => loadPPPoE(false), 1000);
  1008. }
  1009. } catch (err) {
  1010. showToast('Error', err.message, 'error');
  1011. }
  1012. }
  1013. async function togglePPPoEState(name, enable) {
  1014. try {
  1015. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/state`, {
  1016. method: 'POST',
  1017. headers: { 'Content-Type': 'application/json' },
  1018. body: JSON.stringify({ enabled: enable })
  1019. });
  1020. if (res.ok) {
  1021. showToast(enable ? 'Enabled' : 'Disabled', `${name} is now ${enable ? 'enabled' : 'disabled'}`, 'info');
  1022. loadPPPoE(false);
  1023. }
  1024. } catch (err) {
  1025. showToast('Error', err.message, 'error');
  1026. }
  1027. }
  1028. async function deletePPPoEInstance(name) {
  1029. if (!confirm(`Are you sure you want to delete PPPoE client ${name}?`)) return;
  1030. try {
  1031. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1032. if (res.ok) {
  1033. showToast('Deleted', `PPPoE client ${name} removed`, 'success');
  1034. loadPPPoE(false);
  1035. fetchData(false);
  1036. }
  1037. } catch (err) {
  1038. showToast('Error', err.message, 'error');
  1039. }
  1040. }
  1041. // ======================== WireGuard Multi-Interface & Multi-Peer ========================
  1042. state.wgSubTab = 'ifaces';
  1043. function switchWGSubTab(tab) {
  1044. state.wgSubTab = tab;
  1045. const ifacesPanel = document.getElementById('wg-subtab-ifaces');
  1046. const peersPanel = document.getElementById('wg-subtab-peers');
  1047. const ifacesBtn = document.getElementById('wg-subtab-btn-ifaces');
  1048. const peersBtn = document.getElementById('wg-subtab-btn-peers');
  1049. if (tab === 'ifaces') {
  1050. ifacesPanel?.classList.remove('hidden');
  1051. peersPanel?.classList.add('hidden');
  1052. 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';
  1053. 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';
  1054. } else {
  1055. ifacesPanel?.classList.add('hidden');
  1056. peersPanel?.classList.remove('hidden');
  1057. 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';
  1058. 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';
  1059. renderWGPeers();
  1060. }
  1061. }
  1062. async function loadWireGuard(populateInputs = true) {
  1063. try {
  1064. const [ifacesRes, peersRes] = await Promise.all([
  1065. fetch(`${API_BASE}/vpn/wireguard/interfaces`),
  1066. fetch(`${API_BASE}/vpn/wireguard/peers`)
  1067. ]);
  1068. const ifaces = ifacesRes.ok ? await ifacesRes.json() : [];
  1069. const peers = peersRes.ok ? await peersRes.json() : [];
  1070. state.wgInterfaces = Array.isArray(ifaces) ? ifaces : [];
  1071. state.wgPeers = Array.isArray(peers) ? peers : [];
  1072. // Badges
  1073. const ifacesCountBadge = document.getElementById('wg-ifaces-count');
  1074. if (ifacesCountBadge) ifacesCountBadge.innerText = `${state.wgInterfaces.length} Interfaces`;
  1075. const peersCountBadge = document.getElementById('wg-peers-count');
  1076. if (peersCountBadge) peersCountBadge.innerText = `${state.wgPeers.length} Peers`;
  1077. const subTabIfaces = document.getElementById('wg-subtab-badge-ifaces');
  1078. if (subTabIfaces) subTabIfaces.innerText = state.wgInterfaces.length;
  1079. const subTabPeers = document.getElementById('wg-subtab-badge-peers');
  1080. if (subTabPeers) subTabPeers.innerText = state.wgPeers.length;
  1081. // Render Interfaces
  1082. const ifacesTbody = document.getElementById('wg-ifaces-table-body');
  1083. const ifacesEmpty = document.getElementById('wg-ifaces-empty');
  1084. if (ifacesTbody) {
  1085. ifacesTbody.innerHTML = '';
  1086. if (state.wgInterfaces.length === 0) {
  1087. if (ifacesEmpty) ifacesEmpty.classList.remove('hidden');
  1088. } else {
  1089. if (ifacesEmpty) ifacesEmpty.classList.add('hidden');
  1090. state.wgInterfaces.forEach(iface => {
  1091. const peersOnIface = state.wgPeers.filter(p => p.interface === iface.name).length;
  1092. const tr = document.createElement('tr');
  1093. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1094. tr.innerHTML = `
  1095. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(iface.running, iface.disabled)}</td>
  1096. <td class="py-2.5 px-3">
  1097. <div class="flex items-center gap-1.5">
  1098. <span class="font-bold text-white">${escapeHtml(iface.name)}</span>
  1099. ${iface.comment ? `<span class="text-[10px] text-slate-400 font-sans italic">(${escapeHtml(iface.comment)})</span>` : ''}
  1100. </div>
  1101. </td>
  1102. <td class="py-2.5 px-3 text-amber-400 font-mono">${iface.listen_port}</td>
  1103. <td class="py-2.5 px-3 text-emerald-400 font-mono">${iface.address || '<span class="text-slate-600 font-sans">--</span>'}</td>
  1104. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1105. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${iface.public_key}', 'Public Key')" title="Click to copy: ${iface.public_key}">
  1106. ${(iface.public_key || '').substring(0, 10)}... 📋
  1107. </span>
  1108. </td>
  1109. <td class="py-2.5 px-3 text-slate-400 font-mono">${iface.mtu || 1420}</td>
  1110. <td class="py-2.5 px-3 text-center">
  1111. <span class="px-2 py-0.5 rounded text-[10px] font-sans bg-slate-800 text-slate-300">${peersOnIface} peer${peersOnIface !== 1 ? 's' : ''}</span>
  1112. </td>
  1113. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  1114. ${iface.running ? `
  1115. <button onclick="stopWGInterface('${iface.name}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Stop</button>
  1116. ` : `
  1117. <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>
  1118. `}
  1119. <button onclick="toggleWGInterfaceState('${iface.name}', ${iface.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white font-medium">
  1120. ${iface.disabled ? 'Enable' : 'Disable'}
  1121. </button>
  1122. <button onclick="openEditWGInterfaceModal('${iface.name}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1123. <button onclick="deleteWGInterface('${iface.name}')" class="text-xs text-slate-500 hover:text-rose-400 font-medium">Delete</button>
  1124. </td>
  1125. `;
  1126. ifacesTbody.appendChild(tr);
  1127. });
  1128. }
  1129. }
  1130. // Populate filter dropdown in peers tab
  1131. const filterSel = document.getElementById('wg-peers-filter-iface');
  1132. if (filterSel) {
  1133. const currentVal = filterSel.value;
  1134. filterSel.innerHTML = '<option value="">All Interfaces</option>';
  1135. state.wgInterfaces.forEach(i => {
  1136. const opt = document.createElement('option');
  1137. opt.value = i.name;
  1138. opt.innerText = i.name;
  1139. if (i.name === currentVal) opt.selected = true;
  1140. filterSel.appendChild(opt);
  1141. });
  1142. }
  1143. renderWGPeers();
  1144. } catch (err) {
  1145. console.error('Failed to load WireGuard:', err);
  1146. }
  1147. }
  1148. function renderWGPeers() {
  1149. const filterSel = document.getElementById('wg-peers-filter-iface');
  1150. const selectedIface = filterSel ? filterSel.value : '';
  1151. const tbody = document.getElementById('wg-peers-table-body');
  1152. const empty = document.getElementById('wg-peers-empty');
  1153. if (!tbody) return;
  1154. tbody.innerHTML = '';
  1155. const filtered = selectedIface ? state.wgPeers.filter(p => p.interface === selectedIface) : state.wgPeers;
  1156. if (filtered.length === 0) {
  1157. if (empty) empty.classList.remove('hidden');
  1158. } else {
  1159. if (empty) empty.classList.add('hidden');
  1160. filtered.forEach(p => {
  1161. const isOnline = p.latest_handshake && !p.latest_handshake.includes('Never');
  1162. const tr = document.createElement('tr');
  1163. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1164. tr.innerHTML = `
  1165. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isOnline, p.disabled)}</td>
  1166. <td class="py-2.5 px-3 font-mono font-bold text-rose-400">${escapeHtml(p.interface)}</td>
  1167. <td class="py-2.5 px-3 font-bold text-white font-sans">${escapeHtml(p.name || 'Unnamed')}</td>
  1168. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1169. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${p.public_key}', 'Peer Public Key')" title="${p.public_key}">
  1170. ${(p.public_key || '').substring(0, 10)}... 📋
  1171. </span>
  1172. </td>
  1173. <td class="py-2.5 px-3 text-emerald-400 font-mono font-semibold">${(p.allowed_ips || []).join(', ')}</td>
  1174. <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>
  1175. <td class="py-2.5 px-3 text-slate-300 font-sans">${p.latest_handshake || 'Never'}</td>
  1176. <td class="py-2.5 px-3 font-mono text-[11px]">
  1177. <span class="text-emerald-400">↓ ${p.transfer_rx_human || '0 B'}</span>
  1178. <span class="text-cyan-400 ml-1">↑ ${p.transfer_tx_human || '0 B'}</span>
  1179. </td>
  1180. <td class="py-2.5 px-3 text-right font-sans space-x-2 whitespace-nowrap">
  1181. <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">
  1182. ${p.disabled ? 'Enable' : 'Disable'}
  1183. </button>
  1184. <button onclick="openEditWGPeerModal('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1185. <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>
  1186. <button onclick="deleteWGPeer('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Delete</button>
  1187. </td>
  1188. `;
  1189. tbody.appendChild(tr);
  1190. });
  1191. }
  1192. }
  1193. function openAddWGInterfaceModal() {
  1194. document.getElementById('wg-iface-modal-title').innerText = 'Add WireGuard Interface';
  1195. document.getElementById('wg-iface-modal-edit-orig').value = '';
  1196. const nameEl = document.getElementById('wg-iface-modal-name');
  1197. nameEl.value = `wg${(state.wgInterfaces || []).length}`;
  1198. nameEl.readOnly = false;
  1199. document.getElementById('wg-iface-modal-port').value = 51820 + (state.wgInterfaces || []).length;
  1200. document.getElementById('wg-iface-modal-addr').value = `10.${10 + (state.wgInterfaces || []).length}.0.1/24`;
  1201. document.getElementById('wg-iface-modal-mtu').value = '1420';
  1202. document.getElementById('wg-iface-modal-comment').value = '';
  1203. document.getElementById('wg-iface-modal-pubkey').value = '';
  1204. document.getElementById('wg-iface-modal-privkey').value = '';
  1205. document.getElementById('wg-iface-modal-disabled').checked = false;
  1206. generateWGInterfaceKeys();
  1207. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1208. }
  1209. function openEditWGInterfaceModal(name) {
  1210. const iface = (state.wgInterfaces || []).find(i => i.name === name);
  1211. if (!iface) return;
  1212. document.getElementById('wg-iface-modal-title').innerText = `Edit WireGuard Interface: ${name}`;
  1213. document.getElementById('wg-iface-modal-edit-orig').value = name;
  1214. const nameEl = document.getElementById('wg-iface-modal-name');
  1215. nameEl.value = iface.name;
  1216. nameEl.readOnly = false; // ALLOW RENAMING
  1217. document.getElementById('wg-iface-modal-port').value = iface.listen_port || 51820;
  1218. document.getElementById('wg-iface-modal-addr').value = iface.address || '';
  1219. document.getElementById('wg-iface-modal-mtu').value = iface.mtu || 1420;
  1220. document.getElementById('wg-iface-modal-comment').value = iface.comment || '';
  1221. document.getElementById('wg-iface-modal-pubkey').value = iface.public_key || '';
  1222. document.getElementById('wg-iface-modal-privkey').value = iface.private_key || '';
  1223. document.getElementById('wg-iface-modal-disabled').checked = !!iface.disabled;
  1224. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1225. }
  1226. function closeAddWGInterfaceModal() {
  1227. document.getElementById('wg-iface-modal').classList.add('hidden');
  1228. }
  1229. async function generateWGInterfaceKeys() {
  1230. try {
  1231. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1232. const keys = await res.json();
  1233. if (res.ok) {
  1234. document.getElementById('wg-iface-modal-privkey').value = keys.private_key;
  1235. document.getElementById('wg-iface-modal-pubkey').value = keys.public_key;
  1236. }
  1237. } catch (err) {
  1238. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1239. }
  1240. }
  1241. async function onWGInterfacePrivKeyInput() {
  1242. const privKey = document.getElementById('wg-iface-modal-privkey').value.trim();
  1243. if (!privKey) return;
  1244. try {
  1245. const res = await fetch(`${API_BASE}/vpn/wireguard/calc-pubkey`, {
  1246. method: 'POST',
  1247. headers: { 'Content-Type': 'application/json' },
  1248. body: JSON.stringify({ private_key: privKey })
  1249. });
  1250. if (res.ok) {
  1251. const data = await res.json();
  1252. if (data.public_key) {
  1253. document.getElementById('wg-iface-modal-pubkey').value = data.public_key;
  1254. }
  1255. }
  1256. } catch (err) {
  1257. // Ignore while typing
  1258. }
  1259. }
  1260. function toggleWGPrivKeyVisibility() {
  1261. const el = document.getElementById('wg-iface-modal-privkey');
  1262. const btn = document.getElementById('btn-toggle-wg-privkey');
  1263. if (el.type === 'password') {
  1264. el.type = 'text';
  1265. btn.innerText = '🙈 Hide';
  1266. } else {
  1267. el.type = 'password';
  1268. btn.innerText = '👁️ Show';
  1269. }
  1270. }
  1271. function copyWGInterfacePubKey() {
  1272. const pub = document.getElementById('wg-iface-modal-pubkey').value;
  1273. if (pub) copyToClipboard(pub, 'Interface Public Key');
  1274. }
  1275. async function submitSaveWGInterface(e) {
  1276. e.preventDefault();
  1277. const origName = document.getElementById('wg-iface-modal-edit-orig').value.trim();
  1278. const name = document.getElementById('wg-iface-modal-name').value.trim();
  1279. const port = parseInt(document.getElementById('wg-iface-modal-port').value, 10) || 51820;
  1280. const addr = document.getElementById('wg-iface-modal-addr').value.trim();
  1281. const mtu = parseInt(document.getElementById('wg-iface-modal-mtu').value, 10) || 1420;
  1282. const comment = document.getElementById('wg-iface-modal-comment').value.trim();
  1283. const pub = document.getElementById('wg-iface-modal-pubkey').value.trim();
  1284. const priv = document.getElementById('wg-iface-modal-privkey').value.trim();
  1285. const disabled = document.getElementById('wg-iface-modal-disabled').checked;
  1286. try {
  1287. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces`, {
  1288. method: 'POST',
  1289. headers: { 'Content-Type': 'application/json' },
  1290. body: JSON.stringify({
  1291. orig_name: origName,
  1292. name,
  1293. listen_port: port,
  1294. address: addr,
  1295. mtu,
  1296. comment,
  1297. public_key: pub,
  1298. private_key: priv,
  1299. disabled
  1300. })
  1301. });
  1302. const data = await res.json();
  1303. if (res.ok) {
  1304. showToast('WireGuard Saved', `Interface ${name} configured successfully`, 'success');
  1305. closeAddWGInterfaceModal();
  1306. loadWireGuard(false);
  1307. fetchData(false);
  1308. } else {
  1309. showToast('Error', data.error || 'Failed to save interface', 'error');
  1310. }
  1311. } catch (err) {
  1312. showToast('Error', err.message, 'error');
  1313. }
  1314. }
  1315. async function startWGInterface(name) {
  1316. try {
  1317. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1318. if (res.ok) {
  1319. showToast('Interface UP', `Started WireGuard interface ${name}`, 'success');
  1320. loadWireGuard(false);
  1321. fetchData(false);
  1322. }
  1323. } catch (err) {
  1324. showToast('Error', err.message, 'error');
  1325. }
  1326. }
  1327. async function stopWGInterface(name) {
  1328. try {
  1329. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1330. if (res.ok) {
  1331. showToast('Interface DOWN', `Stopped WireGuard interface ${name}`, 'info');
  1332. loadWireGuard(false);
  1333. fetchData(false);
  1334. }
  1335. } catch (err) {
  1336. showToast('Error', err.message, 'error');
  1337. }
  1338. }
  1339. async function toggleWGInterfaceState(name, enable) {
  1340. try {
  1341. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/state`, {
  1342. method: 'POST',
  1343. headers: { 'Content-Type': 'application/json' },
  1344. body: JSON.stringify({ enabled: enable })
  1345. });
  1346. if (res.ok) {
  1347. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1348. loadWireGuard(false);
  1349. fetchData(false);
  1350. }
  1351. } catch (err) {
  1352. showToast('Error', err.message, 'error');
  1353. }
  1354. }
  1355. async function deleteWGInterface(name) {
  1356. if (!confirm(`Are you sure you want to delete WireGuard interface ${name}? All associated peers will also be removed.`)) return;
  1357. try {
  1358. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1359. if (res.ok) {
  1360. showToast('Deleted', `Interface ${name} removed`, 'success');
  1361. loadWireGuard(false);
  1362. fetchData(false);
  1363. }
  1364. } catch (err) {
  1365. showToast('Error', err.message, 'error');
  1366. }
  1367. }
  1368. function populateWGPeerIfaceSelect(selectedIface = '') {
  1369. const sel = document.getElementById('wg-peer-modal-iface');
  1370. if (!sel) return;
  1371. sel.innerHTML = '';
  1372. (state.wgInterfaces || []).forEach(i => {
  1373. const opt = document.createElement('option');
  1374. opt.value = i.name;
  1375. opt.innerText = `${i.name} (${i.address || 'No IP'})`;
  1376. if (i.name === selectedIface) opt.selected = true;
  1377. sel.appendChild(opt);
  1378. });
  1379. }
  1380. function openAddWGPeerModal() {
  1381. if ((state.wgInterfaces || []).length === 0) {
  1382. showToast('No Interfaces', 'Please add a WireGuard interface first before adding peers', 'warning');
  1383. openAddWGInterfaceModal();
  1384. return;
  1385. }
  1386. document.getElementById('wg-peer-modal-title').innerText = 'Add WireGuard Peer';
  1387. document.getElementById('wg-peer-modal-edit-orig-iface').value = '';
  1388. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = '';
  1389. populateWGPeerIfaceSelect();
  1390. document.getElementById('wg-peer-modal-name').value = '';
  1391. document.getElementById('wg-peer-modal-pubkey').value = '';
  1392. document.getElementById('wg-peer-modal-allowedips').value = '10.10.0.2/32';
  1393. document.getElementById('wg-peer-modal-endpoint').value = '';
  1394. document.getElementById('wg-peer-modal-port').value = '';
  1395. document.getElementById('wg-peer-modal-keepalive').value = '25';
  1396. document.getElementById('wg-peer-modal-preshared').value = '';
  1397. document.getElementById('wg-peer-modal-disabled').checked = false;
  1398. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  1399. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  1400. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1401. }
  1402. function openEditWGPeerModal(ifaceName, pubKey) {
  1403. const peer = (state.wgPeers || []).find(p => p.interface === ifaceName && p.public_key === pubKey);
  1404. if (!peer) {
  1405. showToast('Not Found', 'Peer not found', 'warning');
  1406. return;
  1407. }
  1408. document.getElementById('wg-peer-modal-title').innerText = `Edit WireGuard Peer (${peer.name || ifaceName})`;
  1409. document.getElementById('wg-peer-modal-edit-orig-iface').value = peer.interface;
  1410. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = peer.public_key;
  1411. populateWGPeerIfaceSelect(peer.interface);
  1412. document.getElementById('wg-peer-modal-name').value = peer.name || '';
  1413. document.getElementById('wg-peer-modal-pubkey').value = peer.public_key || '';
  1414. document.getElementById('wg-peer-modal-allowedips').value = (peer.allowed_ips || []).join(', ');
  1415. document.getElementById('wg-peer-modal-endpoint').value = peer.endpoint_address || '';
  1416. document.getElementById('wg-peer-modal-port').value = peer.endpoint_port || '';
  1417. document.getElementById('wg-peer-modal-keepalive').value = peer.persistent_keepalive ?? 25;
  1418. document.getElementById('wg-peer-modal-preshared').value = peer.preshared_key || '';
  1419. document.getElementById('wg-peer-modal-disabled').checked = !!peer.disabled;
  1420. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  1421. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  1422. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1423. }
  1424. function closeAddWGPeerModal() {
  1425. document.getElementById('wg-peer-modal').classList.add('hidden');
  1426. }
  1427. async function generatePeerKeypairHelper() {
  1428. try {
  1429. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1430. const keys = await res.json();
  1431. if (res.ok) {
  1432. document.getElementById('wg-peer-modal-pubkey').value = keys.public_key;
  1433. document.getElementById('wg-peer-gen-privkey').value = keys.private_key;
  1434. document.getElementById('wg-peer-gen-key-box').classList.remove('hidden');
  1435. checkWGPeerKeyValidity();
  1436. showToast('Keypair Generated', 'Public key inserted and client private key ready to copy', 'info');
  1437. }
  1438. } catch (err) {
  1439. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1440. }
  1441. }
  1442. function copyGeneratedPeerPrivKey() {
  1443. const priv = document.getElementById('wg-peer-gen-privkey').value;
  1444. if (priv) copyToClipboard(priv, 'Client Private Key');
  1445. }
  1446. async function generatePeerPSK() {
  1447. try {
  1448. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1449. const keys = await res.json();
  1450. if (res.ok && keys.private_key) {
  1451. document.getElementById('wg-peer-modal-preshared').value = keys.private_key;
  1452. showToast('PSK Generated', 'Generated 256-bit preshared key', 'info');
  1453. }
  1454. } catch (err) {
  1455. showToast('Error', err.message, 'error');
  1456. }
  1457. }
  1458. function checkWGPeerKeyValidity() {
  1459. const ifaceName = document.getElementById('wg-peer-modal-iface').value;
  1460. const peerPubKey = document.getElementById('wg-peer-modal-pubkey').value.trim();
  1461. const warningEl = document.getElementById('wg-peer-key-warning');
  1462. if (!warningEl) return;
  1463. const targetIface = (state.wgInterfaces || []).find(i => i.name === ifaceName);
  1464. if (targetIface && targetIface.public_key && peerPubKey && targetIface.public_key === peerPubKey) {
  1465. warningEl.classList.remove('hidden');
  1466. } else {
  1467. warningEl.classList.add('hidden');
  1468. }
  1469. }
  1470. async function submitSaveWGPeer(e) {
  1471. e.preventDefault();
  1472. const origIface = document.getElementById('wg-peer-modal-edit-orig-iface').value.trim();
  1473. const origPubKey = document.getElementById('wg-peer-modal-edit-orig-pubkey').value.trim();
  1474. const iface = document.getElementById('wg-peer-modal-iface').value;
  1475. const name = document.getElementById('wg-peer-modal-name').value.trim();
  1476. const pub = document.getElementById('wg-peer-modal-pubkey').value.trim();
  1477. const allowed = document.getElementById('wg-peer-modal-allowedips').value
  1478. .split(',')
  1479. .map(s => s.trim())
  1480. .filter(s => s.length > 0);
  1481. const epHost = document.getElementById('wg-peer-modal-endpoint').value.trim();
  1482. const epPort = parseInt(document.getElementById('wg-peer-modal-port').value, 10) || 0;
  1483. const keepalive = parseInt(document.getElementById('wg-peer-modal-keepalive').value, 10) || 0;
  1484. const psk = document.getElementById('wg-peer-modal-preshared').value.trim();
  1485. const disabled = document.getElementById('wg-peer-modal-disabled').checked;
  1486. // Validation
  1487. const targetIface = (state.wgInterfaces || []).find(i => i.name === iface);
  1488. if (targetIface && targetIface.public_key === pub) {
  1489. showToast('Invalid Peer Key', 'Peer public key cannot be the same as the interface public key!', 'error');
  1490. return;
  1491. }
  1492. try {
  1493. const res = await fetch(`${API_BASE}/vpn/wireguard/peers`, {
  1494. method: 'POST',
  1495. headers: { 'Content-Type': 'application/json' },
  1496. body: JSON.stringify({
  1497. orig_interface: origIface,
  1498. orig_public_key: origPubKey,
  1499. interface: iface,
  1500. name,
  1501. public_key: pub,
  1502. allowed_ips: allowed,
  1503. endpoint_address: epHost,
  1504. endpoint_port: epPort,
  1505. persistent_keepalive: keepalive,
  1506. preshared_key: psk,
  1507. disabled
  1508. })
  1509. });
  1510. const data = await res.json();
  1511. if (res.ok) {
  1512. showToast('Peer Saved', `Peer ${name} saved on ${iface}`, 'success');
  1513. closeAddWGPeerModal();
  1514. loadWireGuard(false);
  1515. } else {
  1516. showToast('Error', data.error || 'Failed to save peer', 'error');
  1517. }
  1518. } catch (err) {
  1519. showToast('Error', err.message, 'error');
  1520. }
  1521. }
  1522. async function toggleWGPeerState(iface, pubkey, enable) {
  1523. try {
  1524. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/state`, {
  1525. method: 'POST',
  1526. headers: { 'Content-Type': 'application/json' },
  1527. body: JSON.stringify({ interface: iface, public_key: pubkey, enabled: enable })
  1528. });
  1529. const data = await res.json();
  1530. if (res.ok) {
  1531. showToast(enable ? 'Peer Enabled' : 'Peer Disabled', `Peer state updated on ${iface}`, 'info');
  1532. loadWireGuard(false);
  1533. } else {
  1534. showToast('Error', data.error || 'Failed to update peer state', 'error');
  1535. }
  1536. } catch (err) {
  1537. showToast('Error', err.message, 'error');
  1538. }
  1539. }
  1540. async function deleteWGPeer(iface, pubkey) {
  1541. if (!confirm(`Are you sure you want to remove peer from ${iface}?`)) return;
  1542. try {
  1543. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/delete`, {
  1544. method: 'POST',
  1545. headers: { 'Content-Type': 'application/json' },
  1546. body: JSON.stringify({ interface: iface, public_key: pubkey })
  1547. });
  1548. const data = await res.json();
  1549. if (res.ok) {
  1550. showToast('Peer Deleted', 'WireGuard peer removed', 'success');
  1551. loadWireGuard(false);
  1552. } else {
  1553. showToast('Error', data.error || 'Failed to remove peer', 'error');
  1554. }
  1555. } catch (err) {
  1556. showToast('Error', err.message, 'error');
  1557. }
  1558. }
  1559. // ======================== IPSec Multi-Tunnel ========================
  1560. async function loadIPSec(populateInputs = true) {
  1561. try {
  1562. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`);
  1563. const list = await res.json();
  1564. state.ipsecTunnels = Array.isArray(list) ? list : [];
  1565. const activeCount = state.ipsecTunnels.filter(t => t.running || t.status === 'ESTABLISHED').length;
  1566. const badge = document.getElementById('ipsec-sas-badge');
  1567. if (badge) badge.innerText = `${activeCount} Active SAs`;
  1568. const tbody = document.getElementById('ipsec-table-body');
  1569. const empty = document.getElementById('ipsec-empty');
  1570. if (!tbody) return;
  1571. tbody.innerHTML = '';
  1572. if (state.ipsecTunnels.length === 0) {
  1573. if (empty) empty.classList.remove('hidden');
  1574. } else {
  1575. if (empty) empty.classList.add('hidden');
  1576. state.ipsecTunnels.forEach(c => {
  1577. const isEstablished = c.running || c.status === 'ESTABLISHED';
  1578. const tr = document.createElement('tr');
  1579. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1580. tr.innerHTML = `
  1581. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isEstablished, c.disabled)}</td>
  1582. <td class="py-2.5 px-4 font-bold text-white">${c.name}</td>
  1583. <td class="py-2.5 px-4 text-emerald-400 font-mono">${c.local_subnet || '-'}</td>
  1584. <td class="py-2.5 px-4 text-slate-300 font-mono">${c.remote_addrs || '-'}</td>
  1585. <td class="py-2.5 px-4 text-cyan-400 font-mono">${c.remote_subnet || '-'}</td>
  1586. <td class="py-2.5 px-4 font-sans">
  1587. <span class="px-2 py-0.5 rounded-full text-[10px] font-semibold ${
  1588. isEstablished ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30' : 'bg-slate-800 text-slate-400'
  1589. }">${c.status || (isEstablished ? 'ESTABLISHED' : 'DISCONNECTED')}</span>
  1590. </td>
  1591. <td class="py-2.5 px-4 text-right space-x-2 font-sans">
  1592. ${isEstablished ? `
  1593. <button onclick="stopIPSecTunnel('${c.name}')" class="text-xs text-rose-400 hover:text-rose-300">Terminate</button>
  1594. ` : `
  1595. <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>
  1596. `}
  1597. <button onclick="toggleIPSecState('${c.name}', ${c.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1598. ${c.disabled ? 'Enable' : 'Disable'}
  1599. </button>
  1600. <button onclick="openEditIPSecModal('${c.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1601. <button onclick="deleteIPSecConn('${c.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1602. </td>
  1603. `;
  1604. tbody.appendChild(tr);
  1605. });
  1606. }
  1607. } catch (err) {
  1608. console.error('Failed to load IPSec:', err);
  1609. }
  1610. }
  1611. function openAddIPSecModal() {
  1612. document.getElementById('ipsec-modal-title').innerText = 'Configure IPSec IKEv2 Tunnel';
  1613. document.getElementById('ipsec-modal-name').value = `ipsec-${(state.ipsecTunnels || []).length + 1}`;
  1614. document.getElementById('ipsec-modal-name').readOnly = false;
  1615. document.getElementById('ipsec-modal-localts').value = '192.168.10.0/24';
  1616. document.getElementById('ipsec-modal-remotets').value = '192.168.20.0/24';
  1617. document.getElementById('ipsec-modal-remotegw').value = '';
  1618. document.getElementById('ipsec-modal-psk').value = '';
  1619. document.getElementById('ipsec-modal-ikeprop').value = 'aes256-sha256-modp2048,default';
  1620. document.getElementById('ipsec-modal-espprop').value = 'aes256-sha256-modp2048,default';
  1621. document.getElementById('ipsec-modal-autostart').checked = true;
  1622. document.getElementById('ipsec-modal-disabled').checked = false;
  1623. document.getElementById('ipsec-modal').classList.remove('hidden');
  1624. }
  1625. function openEditIPSecModal(name) {
  1626. const conn = (state.ipsecTunnels || []).find(c => c.name === name);
  1627. if (!conn) return;
  1628. document.getElementById('ipsec-modal-title').innerText = `Edit IPSec Tunnel: ${name}`;
  1629. document.getElementById('ipsec-modal-name').value = conn.name;
  1630. document.getElementById('ipsec-modal-name').readOnly = true;
  1631. document.getElementById('ipsec-modal-localts').value = conn.local_subnet || '';
  1632. document.getElementById('ipsec-modal-remotets').value = conn.remote_subnet || '';
  1633. document.getElementById('ipsec-modal-remotegw').value = conn.remote_addrs || '';
  1634. document.getElementById('ipsec-modal-psk').value = conn.preshared_key || '';
  1635. document.getElementById('ipsec-modal-ikeprop').value = conn.ike_proposals || 'aes256-sha256-modp2048,default';
  1636. document.getElementById('ipsec-modal-espprop').value = conn.esp_proposals || 'aes256-sha256-modp2048,default';
  1637. document.getElementById('ipsec-modal-autostart').checked = conn.auto_start ?? true;
  1638. document.getElementById('ipsec-modal-disabled').checked = !!conn.disabled;
  1639. document.getElementById('ipsec-modal').classList.remove('hidden');
  1640. }
  1641. function closeAddIPSecModal() {
  1642. document.getElementById('ipsec-modal').classList.add('hidden');
  1643. }
  1644. async function submitSaveIPSec(e) {
  1645. e.preventDefault();
  1646. const name = document.getElementById('ipsec-modal-name').value.trim();
  1647. const localts = document.getElementById('ipsec-modal-localts').value.trim();
  1648. const remotets = document.getElementById('ipsec-modal-remotets').value.trim();
  1649. const remotegw = document.getElementById('ipsec-modal-remotegw').value.trim();
  1650. const psk = document.getElementById('ipsec-modal-psk').value;
  1651. const ike = document.getElementById('ipsec-modal-ikeprop').value.trim();
  1652. const esp = document.getElementById('ipsec-modal-espprop').value.trim();
  1653. const autostart = document.getElementById('ipsec-modal-autostart').checked;
  1654. const disabled = document.getElementById('ipsec-modal-disabled').checked;
  1655. try {
  1656. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`, {
  1657. method: 'POST',
  1658. headers: { 'Content-Type': 'application/json' },
  1659. body: JSON.stringify({
  1660. name,
  1661. local_addrs: '%any',
  1662. remote_addrs: remotegw,
  1663. local_subnet: localts,
  1664. remote_subnet: remotets,
  1665. preshared_key: psk,
  1666. ike_proposals: ike,
  1667. esp_proposals: esp,
  1668. auto_start: autostart,
  1669. disabled
  1670. })
  1671. });
  1672. if (res.ok) {
  1673. showToast('IPSec Saved', `Tunnel ${name} configured`, 'success');
  1674. closeAddIPSecModal();
  1675. loadIPSec(false);
  1676. fetchData(false);
  1677. }
  1678. } catch (err) {
  1679. showToast('Error', err.message, 'error');
  1680. }
  1681. }
  1682. async function startIPSecTunnel(name) {
  1683. try {
  1684. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1685. if (res.ok) {
  1686. showToast('Initiating Tunnel', `Attempting SA handshake for ${name}...`, 'info');
  1687. setTimeout(() => loadIPSec(false), 2000);
  1688. }
  1689. } catch (err) {
  1690. showToast('Error', err.message, 'error');
  1691. }
  1692. }
  1693. async function stopIPSecTunnel(name) {
  1694. try {
  1695. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1696. if (res.ok) {
  1697. showToast('Terminated', `IPSec SA for ${name} closed`, 'info');
  1698. loadIPSec(false);
  1699. }
  1700. } catch (err) {
  1701. showToast('Error', err.message, 'error');
  1702. }
  1703. }
  1704. async function toggleIPSecState(name, enable) {
  1705. try {
  1706. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/state`, {
  1707. method: 'POST',
  1708. headers: { 'Content-Type': 'application/json' },
  1709. body: JSON.stringify({ enabled: enable })
  1710. });
  1711. if (res.ok) {
  1712. showToast(enable ? 'Enabled' : 'Disabled', `IPSec tunnel ${name} updated`, 'info');
  1713. loadIPSec(false);
  1714. }
  1715. } catch (err) {
  1716. showToast('Error', err.message, 'error');
  1717. }
  1718. }
  1719. async function deleteIPSecConn(name) {
  1720. if (!confirm(`Are you sure you want to delete IPSec tunnel ${name}?`)) return;
  1721. try {
  1722. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1723. if (res.ok) {
  1724. showToast('Deleted', `IPSec connection ${name} removed`, 'success');
  1725. loadIPSec(false);
  1726. fetchData(false);
  1727. }
  1728. } catch (err) {
  1729. showToast('Error', err.message, 'error');
  1730. }
  1731. }
  1732. // ======================== L2TP Multi-Instance ========================
  1733. async function loadL2TP(populateInputs = true) {
  1734. try {
  1735. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`);
  1736. const list = await res.json();
  1737. state.l2tpList = Array.isArray(list) ? list : [];
  1738. const badge = document.getElementById('l2tp-count-badge');
  1739. if (badge) badge.innerText = `${state.l2tpList.length} Client${state.l2tpList.length !== 1 ? 's' : ''}`;
  1740. const tbody = document.getElementById('l2tp-table-body');
  1741. const empty = document.getElementById('l2tp-empty');
  1742. if (!tbody) return;
  1743. tbody.innerHTML = '';
  1744. if (state.l2tpList.length === 0) {
  1745. if (empty) empty.classList.remove('hidden');
  1746. } else {
  1747. if (empty) empty.classList.add('hidden');
  1748. state.l2tpList.forEach(inst => {
  1749. const tr = document.createElement('tr');
  1750. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1751. tr.innerHTML = `
  1752. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1753. <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
  1754. <td class="py-2.5 px-3 text-cyan-400 font-mono">${inst.connect_to}</td>
  1755. <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
  1756. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
  1757. <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
  1758. <td class="py-2.5 px-3 text-center">
  1759. <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'}">
  1760. ${inst.default_route ? 'Yes' : 'No'}
  1761. </span>
  1762. </td>
  1763. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1764. ${inst.running ? `
  1765. <button onclick="disconnectL2TPInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1766. ` : `
  1767. <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>
  1768. `}
  1769. <button onclick="toggleL2TPState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1770. ${inst.disabled ? 'Enable' : 'Disable'}
  1771. </button>
  1772. <button onclick="openEditL2TPModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1773. <button onclick="deleteL2TPInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1774. </td>
  1775. `;
  1776. tbody.appendChild(tr);
  1777. });
  1778. }
  1779. } catch (err) {
  1780. console.error('Failed to load L2TP:', err);
  1781. }
  1782. }
  1783. function openAddL2TPModal() {
  1784. document.getElementById('l2tp-modal-title').innerText = 'Add L2TP Client Interface';
  1785. document.getElementById('l2tp-modal-name').value = `l2tp-out${(state.l2tpList || []).length + 1}`;
  1786. document.getElementById('l2tp-modal-name').readOnly = false;
  1787. document.getElementById('l2tp-modal-server').value = '';
  1788. document.getElementById('l2tp-modal-user').value = '';
  1789. document.getElementById('l2tp-modal-pass').value = '';
  1790. document.getElementById('l2tp-modal-ipsec').value = '';
  1791. document.getElementById('l2tp-modal-defroute').checked = true;
  1792. document.getElementById('l2tp-modal-disabled').checked = false;
  1793. document.getElementById('l2tp-modal').classList.remove('hidden');
  1794. }
  1795. function openEditL2TPModal(name) {
  1796. const inst = (state.l2tpList || []).find(i => i.name === name);
  1797. if (!inst) return;
  1798. document.getElementById('l2tp-modal-title').innerText = `Edit L2TP Client: ${name}`;
  1799. document.getElementById('l2tp-modal-name').value = inst.name;
  1800. document.getElementById('l2tp-modal-name').readOnly = true;
  1801. document.getElementById('l2tp-modal-server').value = inst.connect_to || '';
  1802. document.getElementById('l2tp-modal-user').value = inst.username || '';
  1803. document.getElementById('l2tp-modal-pass').value = inst.password || '';
  1804. document.getElementById('l2tp-modal-ipsec').value = inst.ipsec_secret || '';
  1805. document.getElementById('l2tp-modal-defroute').checked = inst.default_route ?? true;
  1806. document.getElementById('l2tp-modal-disabled').checked = !!inst.disabled;
  1807. document.getElementById('l2tp-modal').classList.remove('hidden');
  1808. }
  1809. function closeL2TPModal() {
  1810. document.getElementById('l2tp-modal').classList.add('hidden');
  1811. }
  1812. async function submitSaveL2TP(e) {
  1813. e.preventDefault();
  1814. const name = document.getElementById('l2tp-modal-name').value.trim();
  1815. const server = document.getElementById('l2tp-modal-server').value.trim();
  1816. const user = document.getElementById('l2tp-modal-user').value.trim();
  1817. const pass = document.getElementById('l2tp-modal-pass').value;
  1818. const ipsec = document.getElementById('l2tp-modal-ipsec').value;
  1819. const defRoute = document.getElementById('l2tp-modal-defroute').checked;
  1820. const disabled = document.getElementById('l2tp-modal-disabled').checked;
  1821. try {
  1822. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`, {
  1823. method: 'POST',
  1824. headers: { 'Content-Type': 'application/json' },
  1825. body: JSON.stringify({
  1826. name,
  1827. connect_to: server,
  1828. username: user,
  1829. password: pass,
  1830. ipsec_secret: ipsec,
  1831. default_route: defRoute,
  1832. disabled
  1833. })
  1834. });
  1835. if (res.ok) {
  1836. showToast('L2TP Saved', `Client ${name} configuration saved`, 'success');
  1837. closeL2TPModal();
  1838. loadL2TP(false);
  1839. fetchData(false);
  1840. }
  1841. } catch (err) {
  1842. showToast('Error', err.message, 'error');
  1843. }
  1844. }
  1845. async function connectL2TPInstance(name) {
  1846. try {
  1847. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1848. if (res.ok) {
  1849. showToast('Connecting', `Dialing L2TP ${name}...`, 'info');
  1850. setTimeout(() => loadL2TP(false), 2000);
  1851. }
  1852. } catch (err) {
  1853. showToast('Error', err.message, 'error');
  1854. }
  1855. }
  1856. async function disconnectL2TPInstance(name) {
  1857. try {
  1858. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1859. if (res.ok) {
  1860. showToast('Disconnected', `L2TP tunnel ${name} terminated`, 'info');
  1861. loadL2TP(false);
  1862. }
  1863. } catch (err) {
  1864. showToast('Error', err.message, 'error');
  1865. }
  1866. }
  1867. async function toggleL2TPState(name, enable) {
  1868. try {
  1869. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/state`, {
  1870. method: 'POST',
  1871. headers: { 'Content-Type': 'application/json' },
  1872. body: JSON.stringify({ enabled: enable })
  1873. });
  1874. if (res.ok) {
  1875. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1876. loadL2TP(false);
  1877. }
  1878. } catch (err) {
  1879. showToast('Error', err.message, 'error');
  1880. }
  1881. }
  1882. async function deleteL2TPInstance(name) {
  1883. if (!confirm(`Are you sure you want to delete L2TP client ${name}?`)) return;
  1884. try {
  1885. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1886. if (res.ok) {
  1887. showToast('Deleted', `L2TP client ${name} removed`, 'success');
  1888. loadL2TP(false);
  1889. fetchData(false);
  1890. }
  1891. } catch (err) {
  1892. showToast('Error', err.message, 'error');
  1893. }
  1894. }
  1895. // ======================== PPTP Multi-Instance ========================
  1896. async function loadPPTP(populateInputs = true) {
  1897. try {
  1898. const res = await fetch(`${API_BASE}/vpn/pptp/clients`);
  1899. const list = await res.json();
  1900. state.pptpList = Array.isArray(list) ? list : [];
  1901. const badge = document.getElementById('pptp-count-badge');
  1902. if (badge) badge.innerText = `${state.pptpList.length} Client${state.pptpList.length !== 1 ? 's' : ''}`;
  1903. const tbody = document.getElementById('pptp-table-body');
  1904. const empty = document.getElementById('pptp-empty');
  1905. if (!tbody) return;
  1906. tbody.innerHTML = '';
  1907. if (state.pptpList.length === 0) {
  1908. if (empty) empty.classList.remove('hidden');
  1909. } else {
  1910. if (empty) empty.classList.add('hidden');
  1911. state.pptpList.forEach(inst => {
  1912. const tr = document.createElement('tr');
  1913. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1914. tr.innerHTML = `
  1915. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1916. <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
  1917. <td class="py-2.5 px-3 text-purple-400 font-mono">${inst.connect_to}</td>
  1918. <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
  1919. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
  1920. <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
  1921. <td class="py-2.5 px-3 text-center">
  1922. <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'}">
  1923. ${inst.require_mppe ? 'MPPE-128' : 'None'}
  1924. </span>
  1925. </td>
  1926. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1927. ${inst.running ? `
  1928. <button onclick="disconnectPPTPInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1929. ` : `
  1930. <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>
  1931. `}
  1932. <button onclick="togglePPTPState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1933. ${inst.disabled ? 'Enable' : 'Disable'}
  1934. </button>
  1935. <button onclick="openEditPPTPModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1936. <button onclick="deletePPTPInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1937. </td>
  1938. `;
  1939. tbody.appendChild(tr);
  1940. });
  1941. }
  1942. } catch (err) {
  1943. console.error('Failed to load PPTP:', err);
  1944. }
  1945. }
  1946. function openAddPPTPModal() {
  1947. document.getElementById('pptp-modal-title').innerText = 'Add PPTP Client Interface';
  1948. document.getElementById('pptp-modal-name').value = `pptp-out${(state.pptpList || []).length + 1}`;
  1949. document.getElementById('pptp-modal-name').readOnly = false;
  1950. document.getElementById('pptp-modal-server').value = '';
  1951. document.getElementById('pptp-modal-user').value = '';
  1952. document.getElementById('pptp-modal-pass').value = '';
  1953. document.getElementById('pptp-modal-mppe').checked = true;
  1954. document.getElementById('pptp-modal-defroute').checked = true;
  1955. document.getElementById('pptp-modal-disabled').checked = false;
  1956. document.getElementById('pptp-modal').classList.remove('hidden');
  1957. }
  1958. function openEditPPTPModal(name) {
  1959. const inst = (state.pptpList || []).find(i => i.name === name);
  1960. if (!inst) return;
  1961. document.getElementById('pptp-modal-title').innerText = `Edit PPTP Client: ${name}`;
  1962. document.getElementById('pptp-modal-name').value = inst.name;
  1963. document.getElementById('pptp-modal-name').readOnly = true;
  1964. document.getElementById('pptp-modal-server').value = inst.connect_to || '';
  1965. document.getElementById('pptp-modal-user').value = inst.username || '';
  1966. document.getElementById('pptp-modal-pass').value = inst.password || '';
  1967. document.getElementById('pptp-modal-mppe').checked = inst.require_mppe ?? true;
  1968. document.getElementById('pptp-modal-defroute').checked = inst.default_route ?? true;
  1969. document.getElementById('pptp-modal-disabled').checked = !!inst.disabled;
  1970. document.getElementById('pptp-modal').classList.remove('hidden');
  1971. }
  1972. function closePPTPModal() {
  1973. document.getElementById('pptp-modal').classList.add('hidden');
  1974. }
  1975. async function submitSavePPTP(e) {
  1976. e.preventDefault();
  1977. const name = document.getElementById('pptp-modal-name').value.trim();
  1978. const server = document.getElementById('pptp-modal-server').value.trim();
  1979. const user = document.getElementById('pptp-modal-user').value.trim();
  1980. const pass = document.getElementById('pptp-modal-pass').value;
  1981. const mppe = document.getElementById('pptp-modal-mppe').checked;
  1982. const defRoute = document.getElementById('pptp-modal-defroute').checked;
  1983. const disabled = document.getElementById('pptp-modal-disabled').checked;
  1984. try {
  1985. const res = await fetch(`${API_BASE}/vpn/pptp/clients`, {
  1986. method: 'POST',
  1987. headers: { 'Content-Type': 'application/json' },
  1988. body: JSON.stringify({
  1989. name,
  1990. connect_to: server,
  1991. username: user,
  1992. password: pass,
  1993. require_mppe: mppe,
  1994. default_route: defRoute,
  1995. auto_reconnect: true,
  1996. disabled
  1997. })
  1998. });
  1999. if (res.ok) {
  2000. showToast('PPTP Saved', `Client ${name} configuration saved`, 'success');
  2001. closePPTPModal();
  2002. loadPPTP(false);
  2003. fetchData(false);
  2004. }
  2005. } catch (err) {
  2006. showToast('Error', err.message, 'error');
  2007. }
  2008. }
  2009. async function connectPPTPInstance(name) {
  2010. try {
  2011. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2012. if (res.ok) {
  2013. showToast('Connecting', `Dialing PPTP ${name}...`, 'info');
  2014. setTimeout(() => loadPPTP(false), 2000);
  2015. }
  2016. } catch (err) {
  2017. showToast('Error', err.message, 'error');
  2018. }
  2019. }
  2020. async function disconnectPPTPInstance(name) {
  2021. try {
  2022. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2023. if (res.ok) {
  2024. showToast('Disconnected', `PPTP tunnel ${name} terminated`, 'info');
  2025. loadPPTP(false);
  2026. }
  2027. } catch (err) {
  2028. showToast('Error', err.message, 'error');
  2029. }
  2030. }
  2031. async function togglePPTPState(name, enable) {
  2032. try {
  2033. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/state`, {
  2034. method: 'POST',
  2035. headers: { 'Content-Type': 'application/json' },
  2036. body: JSON.stringify({ enabled: enable })
  2037. });
  2038. if (res.ok) {
  2039. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2040. loadPPTP(false);
  2041. }
  2042. } catch (err) {
  2043. showToast('Error', err.message, 'error');
  2044. }
  2045. }
  2046. async function deletePPTPInstance(name) {
  2047. if (!confirm(`Are you sure you want to delete PPTP client ${name}?`)) return;
  2048. try {
  2049. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2050. if (res.ok) {
  2051. showToast('Deleted', `PPTP client ${name} removed`, 'success');
  2052. loadPPTP(false);
  2053. fetchData(false);
  2054. }
  2055. } catch (err) {
  2056. showToast('Error', err.message, 'error');
  2057. }
  2058. }
  2059. // ---------------- Modal & Helper Functions ----------------
  2060. function openVlanModal(defaultParent = '') {
  2061. const select = document.getElementById('vlan-parent');
  2062. select.innerHTML = '';
  2063. const allIfaces = state.interfaces || [];
  2064. const eligible = allIfaces.filter(i => !i.is_vlan && i.name !== 'lo');
  2065. if (eligible.length === 0) {
  2066. allIfaces.forEach(i => eligible.push(i));
  2067. }
  2068. eligible.forEach(i => {
  2069. const opt = document.createElement('option');
  2070. opt.value = i.name;
  2071. opt.innerText = `${i.name} (${i.role || 'Interface'} - ${i.state})`;
  2072. if (i.name === defaultParent) opt.selected = true;
  2073. select.appendChild(opt);
  2074. });
  2075. document.getElementById('vlan-id').value = '';
  2076. document.getElementById('vlan-name').value = '';
  2077. document.getElementById('vlan-ip').value = '';
  2078. document.getElementById('vlan-desc').value = '';
  2079. autoSuggestVlanName();
  2080. document.getElementById('vlan-modal').classList.remove('hidden');
  2081. }
  2082. function closeVlanModal() {
  2083. document.getElementById('vlan-modal').classList.add('hidden');
  2084. }
  2085. function autoSuggestVlanName() {
  2086. const parent = document.getElementById('vlan-parent').value;
  2087. const id = document.getElementById('vlan-id').value;
  2088. const nameInput = document.getElementById('vlan-name');
  2089. if (parent && id) nameInput.placeholder = `${parent}.${id}`;
  2090. }
  2091. function setSubnetPreset(cidr) {
  2092. const ipInput = document.getElementById('vlan-ip');
  2093. const id = document.getElementById('vlan-id').value || '10';
  2094. ipInput.value = `192.168.${id}.1${cidr}`;
  2095. }
  2096. async function submitCreateVlan(e) {
  2097. e.preventDefault();
  2098. const btn = document.getElementById('vlan-submit-btn');
  2099. btn.disabled = true;
  2100. btn.innerText = 'Creating...';
  2101. const parent = document.getElementById('vlan-parent').value;
  2102. const id = parseInt(document.getElementById('vlan-id').value, 10);
  2103. const name = document.getElementById('vlan-name').value.trim();
  2104. const ip = document.getElementById('vlan-ip').value.trim();
  2105. const role = document.getElementById('vlan-role').value;
  2106. const desc = document.getElementById('vlan-desc').value.trim();
  2107. try {
  2108. const res = await fetch(`${API_BASE}/vlans`, {
  2109. method: 'POST',
  2110. headers: { 'Content-Type': 'application/json' },
  2111. body: JSON.stringify({
  2112. parent_name: parent,
  2113. vlan_id: id,
  2114. name: name,
  2115. ip_address: ip,
  2116. role: role,
  2117. description: desc,
  2118. mtu: 1500,
  2119. auto_up: true
  2120. })
  2121. });
  2122. const data = await res.json();
  2123. if (res.ok) {
  2124. showToast('VLAN Created', `Created ${data.name} (VLAN ${data.vlan_id})`, 'success');
  2125. state.expandedParents.add(parent);
  2126. closeVlanModal();
  2127. await fetchData(true);
  2128. if (state.activeTab !== 'interfaces') navigate('interfaces');
  2129. } else {
  2130. showToast('Creation Failed', data.message || 'Failed to create VLAN', 'error');
  2131. }
  2132. } catch (err) {
  2133. showToast('Error', err.message, 'error');
  2134. } finally {
  2135. btn.disabled = false;
  2136. btn.innerText = 'Create VLAN';
  2137. }
  2138. }
  2139. async function confirmDeleteVlan(name) {
  2140. if (!confirm(`Delete VLAN interface ${name}?`)) return;
  2141. try {
  2142. const res = await fetch(`${API_BASE}/vlans/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2143. if (res.ok) {
  2144. showToast('VLAN Deleted', `Interface ${name} removed`, 'success');
  2145. closeIfaceModal();
  2146. fetchData(true);
  2147. }
  2148. } catch (err) {
  2149. showToast('Error', err.message, 'error');
  2150. }
  2151. }
  2152. function openIfaceModal(name) {
  2153. const iface = (state.interfaces || []).find(i => i.name === name);
  2154. if (!iface) return;
  2155. state.currentModalIface = iface.name;
  2156. document.getElementById('modal-iface-name').innerText = iface.name;
  2157. document.getElementById('modal-iface-badge').innerText = iface.is_vlan ? `VLAN ${iface.vlan_id}` : iface.type;
  2158. document.getElementById('modal-iface-mtu').value = iface.mtu;
  2159. document.getElementById('modal-iface-role').value = iface.role || 'LAN';
  2160. document.getElementById('modal-iface-desc').value = iface.description || '';
  2161. const delBtn = document.getElementById('modal-delete-vlan-btn');
  2162. if (iface.is_vlan) {
  2163. delBtn.classList.remove('hidden');
  2164. } else {
  2165. delBtn.classList.add('hidden');
  2166. }
  2167. renderModalIPs(iface);
  2168. document.getElementById('iface-modal').classList.remove('hidden');
  2169. }
  2170. function renderModalIPs(iface) {
  2171. const container = document.getElementById('modal-ip-list');
  2172. container.innerHTML = '';
  2173. const addrs = [...(iface.ipv4 || []), ...(iface.ipv6 || [])];
  2174. if (addrs.length === 0) {
  2175. container.innerHTML = `<span class="text-slate-500 text-xs font-sans">No IP addresses currently bound</span>`;
  2176. return;
  2177. }
  2178. addrs.forEach(addr => {
  2179. const row = document.createElement('div');
  2180. row.className = 'flex items-center justify-between p-2 rounded bg-slate-900 border border-slate-800';
  2181. row.innerHTML = `
  2182. <span class="text-white">${addr}</span>
  2183. <button onclick="removeInterfaceIP('${addr}')" class="text-[11px] text-rose-400 hover:text-rose-300 font-sans">Remove</button>
  2184. `;
  2185. container.appendChild(row);
  2186. });
  2187. }
  2188. function closeIfaceModal() {
  2189. document.getElementById('iface-modal').classList.add('hidden');
  2190. state.currentModalIface = null;
  2191. }
  2192. async function setIfaceState(name, newState) {
  2193. await toggleInterfaceState(name, newState);
  2194. const updated = (state.interfaces || []).find(i => i.name === name);
  2195. if (updated) openIfaceModal(name);
  2196. }
  2197. async function applyMTU() {
  2198. const mtu = parseInt(document.getElementById('modal-iface-mtu').value, 10);
  2199. try {
  2200. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/mtu`, {
  2201. method: 'POST',
  2202. headers: { 'Content-Type': 'application/json' },
  2203. body: JSON.stringify({ mtu })
  2204. });
  2205. if (res.ok) {
  2206. showToast('MTU Applied', `Set MTU to ${mtu} on ${state.currentModalIface}`, 'success');
  2207. fetchData(false);
  2208. }
  2209. } catch (err) {
  2210. showToast('Error', err.message, 'error');
  2211. }
  2212. }
  2213. async function addInterfaceIP() {
  2214. const ip = document.getElementById('modal-new-ip').value.trim();
  2215. if (!ip) return;
  2216. try {
  2217. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  2218. method: 'POST',
  2219. headers: { 'Content-Type': 'application/json' },
  2220. body: JSON.stringify({ ip })
  2221. });
  2222. if (res.ok) {
  2223. showToast('IP Added', `Bound ${ip} to ${state.currentModalIface}`, 'success');
  2224. document.getElementById('modal-new-ip').value = '';
  2225. await fetchData(false);
  2226. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  2227. if (iface) renderModalIPs(iface);
  2228. } else {
  2229. const err = await res.json();
  2230. showToast('Error', err.error || err.message || 'Failed to add IP address', 'error');
  2231. }
  2232. } catch (err) {
  2233. showToast('Error', err.message, 'error');
  2234. }
  2235. }
  2236. async function removeInterfaceIP(ip) {
  2237. if (!confirm(`Remove IP ${ip}?`)) return;
  2238. try {
  2239. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  2240. method: 'DELETE',
  2241. headers: { 'Content-Type': 'application/json' },
  2242. body: JSON.stringify({ ip })
  2243. });
  2244. if (res.ok) {
  2245. showToast('IP Removed', `Removed ${ip}`, 'success');
  2246. await fetchData(false);
  2247. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  2248. if (iface) renderModalIPs(iface);
  2249. }
  2250. } catch (err) {
  2251. showToast('Error', err.message, 'error');
  2252. }
  2253. }
  2254. async function saveInterfaceMetadata() {
  2255. const role = document.getElementById('modal-iface-role').value;
  2256. const desc = document.getElementById('modal-iface-desc').value.trim();
  2257. try {
  2258. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/metadata`, {
  2259. method: 'POST',
  2260. headers: { 'Content-Type': 'application/json' },
  2261. body: JSON.stringify({ role, description: desc })
  2262. });
  2263. if (res.ok) {
  2264. showToast('Saved', 'Metadata updated', 'success');
  2265. closeIfaceModal();
  2266. fetchData(false);
  2267. }
  2268. } catch (err) {
  2269. showToast('Error', err.message, 'error');
  2270. }
  2271. }
  2272. // ======================== MIKROTIK FIREWALL (/ip firewall) ========================
  2273. state.fwSubTab = 'filter';
  2274. state.routesSubTab = 'routes';
  2275. function renderRuleFlag(disabled, hasComment) {
  2276. let flags = '';
  2277. if (disabled) flags += '<span class="text-rose-400 font-bold" title="Disabled">X</span>';
  2278. if (hasComment) flags += '<span class="text-amber-400 font-bold ml-1" title="Has Comment">C</span>';
  2279. return flags || '<span class="text-slate-600">-</span>';
  2280. }
  2281. function renderActionBadge(action) {
  2282. const act = (action || '').toLowerCase();
  2283. let color = 'bg-slate-800 text-slate-300';
  2284. if (act === 'accept') color = 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30';
  2285. else if (act === 'drop' || act === 'reject') color = 'bg-rose-500/20 text-rose-300 border border-rose-500/30';
  2286. else if (act === 'masquerade' || act === 'src-nat' || act === 'dst-nat') color = 'bg-amber-500/20 text-amber-300 border border-amber-500/30';
  2287. else if (act.startsWith('mark-')) color = 'bg-purple-500/20 text-purple-300 border border-purple-500/30';
  2288. else if (act === 'log') color = 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30';
  2289. return `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold ${color}">${action}</span>`;
  2290. }
  2291. function switchFWSubTab(tab) {
  2292. state.fwSubTab = tab;
  2293. const tabs = ['filter', 'nat', 'mangle', 'addrlist', 'geo', 'connections'];
  2294. tabs.forEach(t => {
  2295. const panel = document.getElementById(`fw-subtab-${t}`);
  2296. const btn = document.getElementById(`fw-subtab-btn-${t}`);
  2297. if (panel) {
  2298. if (t === tab) panel.classList.remove('hidden');
  2299. else panel.classList.add('hidden');
  2300. }
  2301. if (btn) {
  2302. if (t === tab) {
  2303. 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';
  2304. } else {
  2305. 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';
  2306. }
  2307. }
  2308. });
  2309. const addBtn = document.getElementById('fw-primary-add-btn');
  2310. if (addBtn) {
  2311. if (tab === 'filter') addBtn.innerHTML = '<span>+ Add Filter Rule</span>';
  2312. else if (tab === 'nat') addBtn.innerHTML = '<span>+ Add NAT Rule</span>';
  2313. else if (tab === 'mangle') addBtn.innerHTML = '<span>+ Add Mangle Rule</span>';
  2314. else if (tab === 'addrlist') addBtn.innerHTML = '<span>+ Add Address List</span>';
  2315. else if (tab === 'geo') addBtn.innerHTML = '<span>⚙️ Schedule Settings</span>';
  2316. else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
  2317. }
  2318. if (tab === 'geo') loadGeoIP();
  2319. if (tab === 'connections') loadConnections();
  2320. }
  2321. function openCurrentFWModal() {
  2322. if (state.fwSubTab === 'filter') openAddFilterModal();
  2323. else if (state.fwSubTab === 'nat') openAddNATModal();
  2324. else if (state.fwSubTab === 'mangle') openAddMangleModal();
  2325. else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
  2326. else if (state.fwSubTab === 'geo') openGeoIntervalModal();
  2327. else if (state.fwSubTab === 'connections') loadConnections();
  2328. }
  2329. async function loadFirewall(populateDropdowns = true) {
  2330. try {
  2331. const [summaryRes, filterRes, natRes, mangleRes, addrlistRes, geoStatusRes, geoCountriesRes] = await Promise.all([
  2332. fetch(`${API_BASE}/firewall/summary`),
  2333. fetch(`${API_BASE}/firewall/filter`),
  2334. fetch(`${API_BASE}/firewall/nat`),
  2335. fetch(`${API_BASE}/firewall/mangle`),
  2336. fetch(`${API_BASE}/firewall/address-lists`),
  2337. fetch(`${API_BASE}/firewall/geoip/status`),
  2338. fetch(`${API_BASE}/firewall/geoip/countries`)
  2339. ]);
  2340. if (summaryRes.ok) state.fwSummary = await summaryRes.json();
  2341. if (filterRes.ok) state.filterRules = await filterRes.json();
  2342. if (natRes.ok) state.natRules = await natRes.json();
  2343. if (mangleRes.ok) state.mangleRules = await mangleRes.json();
  2344. if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
  2345. if (geoStatusRes.ok) state.geoStatus = await geoStatusRes.json();
  2346. if (geoCountriesRes.ok) state.geoCountries = await geoCountriesRes.json();
  2347. // Badges
  2348. const bFilter = document.getElementById('fw-badge-filter');
  2349. if (bFilter) bFilter.innerText = (state.filterRules || []).length;
  2350. const bNat = document.getElementById('fw-badge-nat');
  2351. if (bNat) bNat.innerText = (state.natRules || []).length;
  2352. const bMangle = document.getElementById('fw-badge-mangle');
  2353. if (bMangle) bMangle.innerText = (state.mangleRules || []).length;
  2354. const bAddr = document.getElementById('fw-badge-addrlist');
  2355. if (bAddr) bAddr.innerText = (state.addressLists || []).length;
  2356. const bGeo = document.getElementById('fw-badge-geo');
  2357. if (bGeo) bGeo.innerText = state.geoStatus?.enabled_count || 0;
  2358. renderFilterRules();
  2359. renderNATRules();
  2360. renderMangleRules();
  2361. renderAddressLists();
  2362. renderGeoCountries();
  2363. if (state.fwSubTab === 'connections') {
  2364. loadConnections();
  2365. }
  2366. } catch (err) {
  2367. console.error('Failed to load firewall:', err);
  2368. }
  2369. }
  2370. // ----------------- Filter Rules -----------------
  2371. function renderFilterRules() {
  2372. const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
  2373. const tbody = document.getElementById('filter-table-body');
  2374. const empty = document.getElementById('filter-empty');
  2375. if (!tbody) return;
  2376. tbody.innerHTML = '';
  2377. const rules = (state.filterRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2378. document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
  2379. if (rules.length === 0) {
  2380. empty?.classList.remove('hidden');
  2381. return;
  2382. }
  2383. empty?.classList.add('hidden');
  2384. rules.forEach((r, idx) => {
  2385. const tr = document.createElement('tr');
  2386. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2387. const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
  2388. const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
  2389. tr.innerHTML = `
  2390. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  2391. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  2392. <td class="py-2.5 px-3 font-bold text-white">${r.chain}</td>
  2393. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  2394. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  2395. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}</td>
  2396. <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
  2397. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  2398. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  2399. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2400. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2401. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2402. </td>
  2403. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2404. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2405. <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2406. <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2407. <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>
  2408. <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2409. <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2410. </td>
  2411. `;
  2412. tbody.appendChild(tr);
  2413. });
  2414. }
  2415. function formatTarget(addr, list, geo) {
  2416. const parts = [];
  2417. if (addr) parts.push(`<span>${addr}</span>`);
  2418. if (list) {
  2419. const inv = list.startsWith('!') ? '!' : '';
  2420. const clean = list.replace(/^!/, '');
  2421. 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>`);
  2422. }
  2423. if (geo) {
  2424. const inv = geo.startsWith('!') ? '!' : '';
  2425. const clean = geo.replace(/^!/, '').replace(/^geo:/, '');
  2426. 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>`);
  2427. }
  2428. if (parts.length === 0) return '<span class="text-slate-600">0.0.0.0/0</span>';
  2429. return parts.join(' ');
  2430. }
  2431. function populateInterfaceSelect(selectId, currentVal = '') {
  2432. const sel = document.getElementById(selectId);
  2433. if (!sel) return;
  2434. sel.innerHTML = '<option value="">(Any Interface)</option>';
  2435. (state.interfaces || []).forEach(i => {
  2436. const opt = document.createElement('option');
  2437. opt.value = i.name;
  2438. opt.innerText = `${i.name} (${i.role || i.type})`;
  2439. if (i.name === currentVal) opt.selected = true;
  2440. sel.appendChild(opt);
  2441. });
  2442. }
  2443. function populateAddressListSelect(selectId, currentVal = '') {
  2444. const sel = document.getElementById(selectId);
  2445. if (!sel) return;
  2446. sel.innerHTML = '<option value="">(None)</option>';
  2447. const cleanVal = (currentVal || '').replace(/^!/, '');
  2448. const customNames = Array.from(new Set((state.addressLists || []).map(a => a.name))).sort();
  2449. customNames.forEach(name => {
  2450. const count = (state.addressLists || []).filter(a => a.name === name).length;
  2451. const opt = document.createElement('option');
  2452. opt.value = name;
  2453. opt.innerText = `${name} (${count} entries)`;
  2454. if (name === cleanVal) opt.selected = true;
  2455. sel.appendChild(opt);
  2456. });
  2457. if (cleanVal && !sel.querySelector(`option[value="${cleanVal}"]`)) {
  2458. const opt = document.createElement('option');
  2459. opt.value = cleanVal;
  2460. opt.innerText = cleanVal;
  2461. opt.selected = true;
  2462. sel.appendChild(opt);
  2463. }
  2464. }
  2465. function populateGeoIPSelect(selectId, currentVal = '') {
  2466. const sel = document.getElementById(selectId);
  2467. if (!sel) return;
  2468. sel.innerHTML = '<option value="">(None)</option>';
  2469. const cleanVal = (currentVal || '').replace(/^!/, '').replace(/^geo:/, '').toUpperCase();
  2470. // Presets optgroup
  2471. const grpPresets = document.createElement('optgroup');
  2472. grpPresets.label = '⚡ Regional Presets';
  2473. const presets = [
  2474. { code: 'EU', label: '🇪🇺 European Union (EU - 27 countries)' },
  2475. { code: 'BALKANS', label: '🏛️ Balkans (GR, CY, BG, RO, AL, etc.)' },
  2476. { code: 'BLOCKLIST', label: '🛡️ High-Risk Blocklist (CN, RU, IR, KP, BY)' }
  2477. ];
  2478. presets.forEach(p => {
  2479. const opt = document.createElement('option');
  2480. opt.value = p.code;
  2481. opt.innerText = p.label;
  2482. if (p.code === cleanVal) opt.selected = true;
  2483. grpPresets.appendChild(opt);
  2484. });
  2485. sel.appendChild(grpPresets);
  2486. // All Countries optgroup
  2487. const grpCountries = document.createElement('optgroup');
  2488. grpCountries.label = '🌍 All Countries';
  2489. const countries = (state.geoCountries || []).slice().sort((a, b) => a.name.localeCompare(b.name));
  2490. countries.forEach(c => {
  2491. const opt = document.createElement('option');
  2492. opt.value = c.code;
  2493. const subnetsInfo = c.subnet_count ? ` [${c.subnet_count.toLocaleString()} subnets]` : '';
  2494. opt.innerText = `${c.name} (${c.code})${subnetsInfo}`;
  2495. if (c.code === cleanVal) opt.selected = true;
  2496. grpCountries.appendChild(opt);
  2497. });
  2498. sel.appendChild(grpCountries);
  2499. }
  2500. function openAddFilterModal() {
  2501. document.getElementById('filter-modal-title').innerText = 'Add Firewall Filter Rule';
  2502. document.getElementById('filter-modal-id').value = '';
  2503. document.getElementById('filter-modal-chain').value = 'forward';
  2504. document.getElementById('filter-modal-action').value = 'accept';
  2505. document.getElementById('filter-modal-proto').value = 'all';
  2506. document.getElementById('filter-modal-src').value = '';
  2507. document.getElementById('filter-modal-dst').value = '';
  2508. document.getElementById('filter-modal-sport').value = '';
  2509. document.getElementById('filter-modal-dport').value = '';
  2510. document.getElementById('filter-modal-connmark').value = '';
  2511. document.getElementById('filter-modal-comment').value = '';
  2512. document.getElementById('filter-modal-disabled').checked = false;
  2513. document.getElementById('filter-modal-cs-established').checked = false;
  2514. document.getElementById('filter-modal-cs-related').checked = false;
  2515. document.getElementById('filter-modal-cs-new').checked = false;
  2516. document.getElementById('filter-modal-cs-invalid').checked = false;
  2517. populateInterfaceSelect('filter-modal-iniface');
  2518. populateInterfaceSelect('filter-modal-outiface');
  2519. if (document.getElementById('filter-modal-srclist-inv')) document.getElementById('filter-modal-srclist-inv').checked = false;
  2520. if (document.getElementById('filter-modal-dstlist-inv')) document.getElementById('filter-modal-dstlist-inv').checked = false;
  2521. populateAddressListSelect('filter-modal-srclist');
  2522. populateAddressListSelect('filter-modal-dstlist');
  2523. if (document.getElementById('filter-modal-srcgeoip-inv')) document.getElementById('filter-modal-srcgeoip-inv').checked = false;
  2524. if (document.getElementById('filter-modal-dstgeoip-inv')) document.getElementById('filter-modal-dstgeoip-inv').checked = false;
  2525. populateGeoIPSelect('filter-modal-srcgeoip');
  2526. populateGeoIPSelect('filter-modal-dstgeoip');
  2527. toggleFilterActionFields();
  2528. document.getElementById('filter-modal').classList.remove('hidden');
  2529. }
  2530. function openEditFilterModal(id) {
  2531. const r = (state.filterRules || []).find(rule => rule.id === id);
  2532. if (!r) return;
  2533. document.getElementById('filter-modal-title').innerText = `Edit Filter Rule (#${r.order})`;
  2534. document.getElementById('filter-modal-id').value = r.id;
  2535. document.getElementById('filter-modal-chain').value = r.chain || 'forward';
  2536. document.getElementById('filter-modal-action').value = r.action || 'accept';
  2537. document.getElementById('filter-modal-proto').value = r.protocol || 'all';
  2538. document.getElementById('filter-modal-src').value = r.src_address || '';
  2539. document.getElementById('filter-modal-dst').value = r.dst_address || '';
  2540. document.getElementById('filter-modal-sport').value = r.src_port || '';
  2541. document.getElementById('filter-modal-dport').value = r.dst_port || '';
  2542. document.getElementById('filter-modal-connmark').value = r.connection_mark || '';
  2543. document.getElementById('filter-modal-comment').value = r.comment || '';
  2544. document.getElementById('filter-modal-disabled').checked = !!r.disabled;
  2545. const states = r.connection_state || [];
  2546. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  2547. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  2548. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  2549. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  2550. populateInterfaceSelect('filter-modal-iniface', r.in_interface);
  2551. populateInterfaceSelect('filter-modal-outiface', r.out_interface);
  2552. const srcInv = (r.src_address_list || '').startsWith('!');
  2553. const dstInv = (r.dst_address_list || '').startsWith('!');
  2554. if (document.getElementById('filter-modal-srclist-inv')) document.getElementById('filter-modal-srclist-inv').checked = srcInv;
  2555. if (document.getElementById('filter-modal-dstlist-inv')) document.getElementById('filter-modal-dstlist-inv').checked = dstInv;
  2556. populateAddressListSelect('filter-modal-srclist', r.src_address_list || '');
  2557. populateAddressListSelect('filter-modal-dstlist', r.dst_address_list || '');
  2558. const srcGeoInv = (r.src_geoip || '').startsWith('!');
  2559. const dstGeoInv = (r.dst_geoip || '').startsWith('!');
  2560. if (document.getElementById('filter-modal-srcgeoip-inv')) document.getElementById('filter-modal-srcgeoip-inv').checked = srcGeoInv;
  2561. if (document.getElementById('filter-modal-dstgeoip-inv')) document.getElementById('filter-modal-dstgeoip-inv').checked = dstGeoInv;
  2562. populateGeoIPSelect('filter-modal-srcgeoip', r.src_geoip || '');
  2563. populateGeoIPSelect('filter-modal-dstgeoip', r.dst_geoip || '');
  2564. toggleFilterActionFields();
  2565. document.getElementById('filter-modal').classList.remove('hidden');
  2566. }
  2567. function closeFilterModal() {
  2568. document.getElementById('filter-modal').classList.add('hidden');
  2569. }
  2570. function toggleFilterActionFields() {
  2571. const act = document.getElementById('filter-modal-action').value;
  2572. const rejectBox = document.getElementById('filter-action-reject-box');
  2573. if (rejectBox) {
  2574. if (act === 'reject') rejectBox.classList.remove('hidden');
  2575. else rejectBox.classList.add('hidden');
  2576. }
  2577. }
  2578. async function submitSaveFilterRule(e) {
  2579. e.preventDefault();
  2580. const id = document.getElementById('filter-modal-id').value;
  2581. const chain = document.getElementById('filter-modal-chain').value;
  2582. const action = document.getElementById('filter-modal-action').value;
  2583. const proto = document.getElementById('filter-modal-proto').value;
  2584. const src = document.getElementById('filter-modal-src').value.trim();
  2585. const dst = document.getElementById('filter-modal-dst').value.trim();
  2586. const sport = document.getElementById('filter-modal-sport').value.trim();
  2587. const dport = document.getElementById('filter-modal-dport').value.trim();
  2588. const inIface = document.getElementById('filter-modal-iniface').value;
  2589. const outIface = document.getElementById('filter-modal-outiface').value;
  2590. const connmark = document.getElementById('filter-modal-connmark').value.trim();
  2591. let srclist = document.getElementById('filter-modal-srclist')?.value || '';
  2592. if (srclist && document.getElementById('filter-modal-srclist-inv')?.checked) {
  2593. srclist = '!' + srclist.replace(/^!/, '');
  2594. }
  2595. let dstlist = document.getElementById('filter-modal-dstlist')?.value || '';
  2596. if (dstlist && document.getElementById('filter-modal-dstlist-inv')?.checked) {
  2597. dstlist = '!' + dstlist.replace(/^!/, '');
  2598. }
  2599. let srcgeoip = document.getElementById('filter-modal-srcgeoip')?.value || '';
  2600. if (srcgeoip && document.getElementById('filter-modal-srcgeoip-inv')?.checked) {
  2601. srcgeoip = '!' + srcgeoip.replace(/^!/, '');
  2602. }
  2603. let dstgeoip = document.getElementById('filter-modal-dstgeoip')?.value || '';
  2604. if (dstgeoip && document.getElementById('filter-modal-dstgeoip-inv')?.checked) {
  2605. dstgeoip = '!' + dstgeoip.replace(/^!/, '');
  2606. }
  2607. const comment = document.getElementById('filter-modal-comment').value.trim();
  2608. const disabled = document.getElementById('filter-modal-disabled').checked;
  2609. const rejectWith = document.getElementById('filter-modal-rejectwith')?.value || '';
  2610. const states = [];
  2611. if (document.getElementById('filter-modal-cs-established').checked) states.push('established');
  2612. if (document.getElementById('filter-modal-cs-related').checked) states.push('related');
  2613. if (document.getElementById('filter-modal-cs-new').checked) states.push('new');
  2614. if (document.getElementById('filter-modal-cs-invalid').checked) states.push('invalid');
  2615. try {
  2616. const res = await fetch(`${API_BASE}/firewall/filter`, {
  2617. method: 'POST',
  2618. headers: { 'Content-Type': 'application/json' },
  2619. body: JSON.stringify({
  2620. id,
  2621. chain,
  2622. action,
  2623. reject_with: rejectWith,
  2624. protocol: proto,
  2625. src_address: src,
  2626. dst_address: dst,
  2627. src_port: sport,
  2628. dst_port: dport,
  2629. in_interface: inIface,
  2630. out_interface: outIface,
  2631. connection_state: states,
  2632. connection_mark: connmark,
  2633. src_address_list: srclist,
  2634. dst_address_list: dstlist,
  2635. src_geoip: srcgeoip,
  2636. dst_geoip: dstgeoip,
  2637. comment,
  2638. disabled
  2639. })
  2640. });
  2641. if (res.ok) {
  2642. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  2643. closeFilterModal();
  2644. loadFirewall(false);
  2645. } else {
  2646. const err = await res.json();
  2647. showToast('Error', err.message, 'error');
  2648. }
  2649. } catch (err) {
  2650. showToast('Error', err.message, 'error');
  2651. }
  2652. }
  2653. async function moveFilterRule(id, dir) {
  2654. try {
  2655. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  2656. method: 'POST',
  2657. headers: { 'Content-Type': 'application/json' },
  2658. body: JSON.stringify({ direction: dir })
  2659. });
  2660. if (res.ok) loadFirewall(false);
  2661. } catch (err) {
  2662. showToast('Error', err.message, 'error');
  2663. }
  2664. }
  2665. async function toggleFilterRuleState(id, disabled) {
  2666. try {
  2667. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  2668. method: 'POST',
  2669. headers: { 'Content-Type': 'application/json' },
  2670. body: JSON.stringify({ disabled })
  2671. });
  2672. if (res.ok) loadFirewall(false);
  2673. } catch (err) {
  2674. showToast('Error', err.message, 'error');
  2675. }
  2676. }
  2677. async function deleteFilterRule(id) {
  2678. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  2679. try {
  2680. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  2681. if (res.ok) {
  2682. showToast('Deleted', 'Filter rule removed', 'success');
  2683. loadFirewall(false);
  2684. }
  2685. } catch (err) {
  2686. showToast('Error', err.message, 'error');
  2687. }
  2688. }
  2689. // ----------------- NAT Rules -----------------
  2690. function renderNATRules() {
  2691. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  2692. const tbody = document.getElementById('nat-table-body');
  2693. const empty = document.getElementById('nat-empty');
  2694. if (!tbody) return;
  2695. tbody.innerHTML = '';
  2696. const rules = (state.natRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2697. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  2698. if (rules.length === 0) {
  2699. empty?.classList.remove('hidden');
  2700. return;
  2701. }
  2702. empty?.classList.add('hidden');
  2703. rules.forEach((r, idx) => {
  2704. const tr = document.createElement('tr');
  2705. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2706. const toTarget = [r.to_addresses, r.to_ports].filter(Boolean).join(':');
  2707. const ifaces = [r.out_interface ? 'out:' + r.out_interface : '', r.in_interface ? 'in:' + r.in_interface : ''].filter(Boolean).join(' ');
  2708. tr.innerHTML = `
  2709. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  2710. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  2711. <td class="py-2.5 px-3 font-bold text-amber-400">${r.chain}</td>
  2712. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  2713. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  2714. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}${r.dst_port ? ':' + r.dst_port : ''}</td>
  2715. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  2716. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  2717. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${toTarget || '-'}</td>
  2718. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2719. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2720. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2721. </td>
  2722. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2723. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2724. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2725. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2726. <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>
  2727. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2728. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2729. </td>
  2730. `;
  2731. tbody.appendChild(tr);
  2732. });
  2733. }
  2734. function openAddNATModal() {
  2735. document.getElementById('nat-modal-title').innerText = 'Add NAT Rule';
  2736. document.getElementById('nat-modal-id').value = '';
  2737. document.getElementById('nat-modal-chain').value = 'srcnat';
  2738. document.getElementById('nat-modal-action').value = 'masquerade';
  2739. document.getElementById('nat-modal-toaddr').value = '';
  2740. document.getElementById('nat-modal-toport').value = '';
  2741. document.getElementById('nat-modal-proto').value = 'all';
  2742. document.getElementById('nat-modal-src').value = '';
  2743. document.getElementById('nat-modal-dst').value = '';
  2744. document.getElementById('nat-modal-dport').value = '';
  2745. document.getElementById('nat-modal-comment').value = '';
  2746. document.getElementById('nat-modal-disabled').checked = false;
  2747. populateInterfaceSelect('nat-modal-iniface');
  2748. populateInterfaceSelect('nat-modal-outiface');
  2749. populateAddressListSelect('nat-modal-srclist');
  2750. populateAddressListSelect('nat-modal-dstlist');
  2751. const srcInvEl = document.getElementById('nat-modal-srclist-inv');
  2752. if (srcInvEl) srcInvEl.checked = false;
  2753. const dstInvEl = document.getElementById('nat-modal-dstlist-inv');
  2754. if (dstInvEl) dstInvEl.checked = false;
  2755. populateGeoIPSelect('nat-modal-srcgeoip');
  2756. populateGeoIPSelect('nat-modal-dstgeoip');
  2757. const srcGeoInvEl = document.getElementById('nat-modal-srcgeoip-inv');
  2758. if (srcGeoInvEl) srcGeoInvEl.checked = false;
  2759. const dstGeoInvEl = document.getElementById('nat-modal-dstgeoip-inv');
  2760. if (dstGeoInvEl) dstGeoInvEl.checked = false;
  2761. toggleNATActionFields();
  2762. document.getElementById('nat-modal').classList.remove('hidden');
  2763. }
  2764. function openEditNATModal(id) {
  2765. const r = (state.natRules || []).find(rule => rule.id === id);
  2766. if (!r) return;
  2767. document.getElementById('nat-modal-title').innerText = `Edit NAT Rule (#${r.order})`;
  2768. document.getElementById('nat-modal-id').value = r.id;
  2769. document.getElementById('nat-modal-chain').value = r.chain || 'srcnat';
  2770. document.getElementById('nat-modal-action').value = r.action || 'masquerade';
  2771. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  2772. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  2773. document.getElementById('nat-modal-proto').value = r.protocol || 'all';
  2774. document.getElementById('nat-modal-src').value = r.src_address || '';
  2775. document.getElementById('nat-modal-dst').value = r.dst_address || '';
  2776. document.getElementById('nat-modal-dport').value = r.dst_port || '';
  2777. document.getElementById('nat-modal-comment').value = r.comment || '';
  2778. document.getElementById('nat-modal-disabled').checked = !!r.disabled;
  2779. populateInterfaceSelect('nat-modal-iniface', r.in_interface);
  2780. populateInterfaceSelect('nat-modal-outiface', r.out_interface);
  2781. const srcInv = (r.src_address_list || '').startsWith('!');
  2782. const dstInv = (r.dst_address_list || '').startsWith('!');
  2783. const srcInvEl = document.getElementById('nat-modal-srclist-inv');
  2784. if (srcInvEl) srcInvEl.checked = srcInv;
  2785. const dstInvEl = document.getElementById('nat-modal-dstlist-inv');
  2786. if (dstInvEl) dstInvEl.checked = dstInv;
  2787. populateAddressListSelect('nat-modal-srclist', r.src_address_list || '');
  2788. populateAddressListSelect('nat-modal-dstlist', r.dst_address_list || '');
  2789. const srcGeoInv = (r.src_geoip || '').startsWith('!');
  2790. const dstGeoInv = (r.dst_geoip || '').startsWith('!');
  2791. const srcGeoInvEl = document.getElementById('nat-modal-srcgeoip-inv');
  2792. if (srcGeoInvEl) srcGeoInvEl.checked = srcGeoInv;
  2793. const dstGeoInvEl = document.getElementById('nat-modal-dstgeoip-inv');
  2794. if (dstGeoInvEl) dstGeoInvEl.checked = dstGeoInv;
  2795. populateGeoIPSelect('nat-modal-srcgeoip', r.src_geoip || '');
  2796. populateGeoIPSelect('nat-modal-dstgeoip', r.dst_geoip || '');
  2797. toggleNATActionFields();
  2798. document.getElementById('nat-modal').classList.remove('hidden');
  2799. }
  2800. function closeNATModal() {
  2801. document.getElementById('nat-modal').classList.add('hidden');
  2802. }
  2803. function toggleNATChainFields() {
  2804. const ch = document.getElementById('nat-modal-chain').value;
  2805. const actSel = document.getElementById('nat-modal-action');
  2806. if (ch === 'srcnat' && actSel.value === 'dst-nat') {
  2807. actSel.value = 'masquerade';
  2808. } else if (ch === 'dstnat' && actSel.value === 'masquerade') {
  2809. actSel.value = 'dst-nat';
  2810. }
  2811. toggleNATActionFields();
  2812. }
  2813. function toggleNATActionFields() {
  2814. const act = document.getElementById('nat-modal-action').value;
  2815. const toBox = document.getElementById('nat-action-to-box');
  2816. if (toBox) {
  2817. if (act === 'masquerade' || act === 'accept') toBox.classList.add('hidden');
  2818. else toBox.classList.remove('hidden');
  2819. }
  2820. }
  2821. async function submitSaveNATRule(e) {
  2822. e.preventDefault();
  2823. const id = document.getElementById('nat-modal-id').value;
  2824. const chain = document.getElementById('nat-modal-chain').value;
  2825. const action = document.getElementById('nat-modal-action').value;
  2826. const toaddr = document.getElementById('nat-modal-toaddr').value.trim();
  2827. const toport = document.getElementById('nat-modal-toport').value.trim();
  2828. const proto = document.getElementById('nat-modal-proto').value;
  2829. const src = document.getElementById('nat-modal-src').value.trim();
  2830. const dst = document.getElementById('nat-modal-dst').value.trim();
  2831. const dport = document.getElementById('nat-modal-dport').value.trim();
  2832. const inIface = document.getElementById('nat-modal-iniface').value;
  2833. const outIface = document.getElementById('nat-modal-outiface').value;
  2834. let srclist = document.getElementById('nat-modal-srclist')?.value || '';
  2835. if (srclist && document.getElementById('nat-modal-srclist-inv')?.checked) {
  2836. srclist = '!' + srclist.replace(/^!/, '');
  2837. }
  2838. let dstlist = document.getElementById('nat-modal-dstlist')?.value || '';
  2839. if (dstlist && document.getElementById('nat-modal-dstlist-inv')?.checked) {
  2840. dstlist = '!' + dstlist.replace(/^!/, '');
  2841. }
  2842. let srcgeoip = document.getElementById('nat-modal-srcgeoip')?.value || '';
  2843. if (srcgeoip && document.getElementById('nat-modal-srcgeoip-inv')?.checked) {
  2844. srcgeoip = '!' + srcgeoip.replace(/^!/, '');
  2845. }
  2846. let dstgeoip = document.getElementById('nat-modal-dstgeoip')?.value || '';
  2847. if (dstgeoip && document.getElementById('nat-modal-dstgeoip-inv')?.checked) {
  2848. dstgeoip = '!' + dstgeoip.replace(/^!/, '');
  2849. }
  2850. const comment = document.getElementById('nat-modal-comment').value.trim();
  2851. const disabled = document.getElementById('nat-modal-disabled').checked;
  2852. try {
  2853. const res = await fetch(`${API_BASE}/firewall/nat`, {
  2854. method: 'POST',
  2855. headers: { 'Content-Type': 'application/json' },
  2856. body: JSON.stringify({
  2857. id,
  2858. chain,
  2859. action,
  2860. to_addresses: toaddr,
  2861. to_ports: toport,
  2862. protocol: proto,
  2863. src_address: src,
  2864. dst_address: dst,
  2865. dst_port: dport,
  2866. in_interface: inIface,
  2867. out_interface: outIface,
  2868. src_address_list: srclist,
  2869. dst_address_list: dstlist,
  2870. src_geoip: srcgeoip,
  2871. dst_geoip: dstgeoip,
  2872. comment,
  2873. disabled
  2874. })
  2875. });
  2876. if (res.ok) {
  2877. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  2878. closeNATModal();
  2879. loadFirewall(false);
  2880. }
  2881. } catch (err) {
  2882. showToast('Error', err.message, 'error');
  2883. }
  2884. }
  2885. async function moveNATRule(id, dir) {
  2886. try {
  2887. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  2888. method: 'POST',
  2889. headers: { 'Content-Type': 'application/json' },
  2890. body: JSON.stringify({ direction: dir })
  2891. });
  2892. if (res.ok) loadFirewall(false);
  2893. } catch (err) {
  2894. showToast('Error', err.message, 'error');
  2895. }
  2896. }
  2897. async function toggleNATRuleState(id, disabled) {
  2898. try {
  2899. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  2900. method: 'POST',
  2901. headers: { 'Content-Type': 'application/json' },
  2902. body: JSON.stringify({ disabled })
  2903. });
  2904. if (res.ok) loadFirewall(false);
  2905. } catch (err) {
  2906. showToast('Error', err.message, 'error');
  2907. }
  2908. }
  2909. async function deleteNATRule(id) {
  2910. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  2911. try {
  2912. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  2913. if (res.ok) {
  2914. showToast('Deleted', 'NAT rule removed', 'success');
  2915. loadFirewall(false);
  2916. }
  2917. } catch (err) {
  2918. showToast('Error', err.message, 'error');
  2919. }
  2920. }
  2921. // ----------------- Mangle Rules -----------------
  2922. function renderMangleRules() {
  2923. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  2924. const tbody = document.getElementById('mangle-table-body');
  2925. const empty = document.getElementById('mangle-empty');
  2926. if (!tbody) return;
  2927. tbody.innerHTML = '';
  2928. const rules = (state.mangleRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2929. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  2930. if (rules.length === 0) {
  2931. empty?.classList.remove('hidden');
  2932. return;
  2933. }
  2934. empty?.classList.add('hidden');
  2935. rules.forEach((r, idx) => {
  2936. const tr = document.createElement('tr');
  2937. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2938. const markVal = r.new_connection_mark || r.new_routing_mark || r.new_packet_mark || r.new_mss || (r.new_dscp ? 'DSCP:' + r.new_dscp : '');
  2939. tr.innerHTML = `
  2940. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  2941. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  2942. <td class="py-2.5 px-3 font-bold text-purple-400">${r.chain}</td>
  2943. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  2944. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  2945. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  2946. <td class="py-2.5 px-3 font-mono font-bold text-cyan-300">${markVal || '-'}</td>
  2947. <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>
  2948. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2949. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2950. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2951. </td>
  2952. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2953. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2954. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2955. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2956. <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>
  2957. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2958. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2959. </td>
  2960. `;
  2961. tbody.appendChild(tr);
  2962. });
  2963. }
  2964. function openAddMangleModal() {
  2965. document.getElementById('mangle-modal-title').innerText = 'Add Mangle Rule';
  2966. document.getElementById('mangle-modal-id').value = '';
  2967. document.getElementById('mangle-modal-chain').value = 'prerouting';
  2968. document.getElementById('mangle-modal-action').value = 'mark-connection';
  2969. document.getElementById('mangle-modal-newmark').value = '';
  2970. document.getElementById('mangle-modal-passthrough').checked = true;
  2971. document.getElementById('mangle-modal-src').value = '';
  2972. document.getElementById('mangle-modal-dst').value = '';
  2973. document.getElementById('mangle-modal-connmark').value = '';
  2974. document.getElementById('mangle-modal-comment').value = '';
  2975. document.getElementById('mangle-modal-disabled').checked = false;
  2976. populateInterfaceSelect('mangle-modal-iniface');
  2977. populateAddressListSelect('mangle-modal-srclist');
  2978. populateAddressListSelect('mangle-modal-dstlist');
  2979. const srcInvEl = document.getElementById('mangle-modal-srclist-inv');
  2980. if (srcInvEl) srcInvEl.checked = false;
  2981. const dstInvEl = document.getElementById('mangle-modal-dstlist-inv');
  2982. if (dstInvEl) dstInvEl.checked = false;
  2983. populateGeoIPSelect('mangle-modal-srcgeoip');
  2984. populateGeoIPSelect('mangle-modal-dstgeoip');
  2985. const srcGeoInvEl = document.getElementById('mangle-modal-srcgeoip-inv');
  2986. if (srcGeoInvEl) srcGeoInvEl.checked = false;
  2987. const dstGeoInvEl = document.getElementById('mangle-modal-dstgeoip-inv');
  2988. if (dstGeoInvEl) dstGeoInvEl.checked = false;
  2989. document.getElementById('mangle-modal').classList.remove('hidden');
  2990. }
  2991. function openEditMangleModal(id) {
  2992. const r = (state.mangleRules || []).find(rule => rule.id === id);
  2993. if (!r) return;
  2994. document.getElementById('mangle-modal-title').innerText = `Edit Mangle Rule (#${r.order})`;
  2995. document.getElementById('mangle-modal-id').value = r.id;
  2996. document.getElementById('mangle-modal-chain').value = r.chain || 'prerouting';
  2997. document.getElementById('mangle-modal-action').value = r.action || 'mark-connection';
  2998. document.getElementById('mangle-modal-newmark').value = r.new_connection_mark || r.new_routing_mark || r.new_packet_mark || r.new_mss || '';
  2999. document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  3000. document.getElementById('mangle-modal-src').value = r.src_address || '';
  3001. document.getElementById('mangle-modal-dst').value = r.dst_address || '';
  3002. document.getElementById('mangle-modal-connmark').value = r.connection_mark || '';
  3003. document.getElementById('mangle-modal-comment').value = r.comment || '';
  3004. document.getElementById('mangle-modal-disabled').checked = !!r.disabled;
  3005. populateInterfaceSelect('mangle-modal-iniface', r.in_interface);
  3006. const srcInv = (r.src_address_list || '').startsWith('!');
  3007. const dstInv = (r.dst_address_list || '').startsWith('!');
  3008. const srcInvEl = document.getElementById('mangle-modal-srclist-inv');
  3009. if (srcInvEl) srcInvEl.checked = srcInv;
  3010. const dstInvEl = document.getElementById('mangle-modal-dstlist-inv');
  3011. if (dstInvEl) dstInvEl.checked = dstInv;
  3012. populateAddressListSelect('mangle-modal-srclist', r.src_address_list || '');
  3013. populateAddressListSelect('mangle-modal-dstlist', r.dst_address_list || '');
  3014. const srcGeoInv = (r.src_geoip || '').startsWith('!');
  3015. const dstGeoInv = (r.dst_geoip || '').startsWith('!');
  3016. const srcGeoInvEl = document.getElementById('mangle-modal-srcgeoip-inv');
  3017. if (srcGeoInvEl) srcGeoInvEl.checked = srcGeoInv;
  3018. const dstGeoInvEl = document.getElementById('mangle-modal-dstgeoip-inv');
  3019. if (dstGeoInvEl) dstGeoInvEl.checked = dstGeoInv;
  3020. populateGeoIPSelect('mangle-modal-srcgeoip', r.src_geoip || '');
  3021. populateGeoIPSelect('mangle-modal-dstgeoip', r.dst_geoip || '');
  3022. document.getElementById('mangle-modal').classList.remove('hidden');
  3023. }
  3024. function closeMangleModal() {
  3025. document.getElementById('mangle-modal').classList.add('hidden');
  3026. }
  3027. function toggleMangleActionFields() {
  3028. // Handled smoothly by single dynamic input
  3029. }
  3030. async function submitSaveMangleRule(e) {
  3031. e.preventDefault();
  3032. const id = document.getElementById('mangle-modal-id').value;
  3033. const chain = document.getElementById('mangle-modal-chain').value;
  3034. const action = document.getElementById('mangle-modal-action').value;
  3035. const newmark = document.getElementById('mangle-modal-newmark').value.trim();
  3036. const passthrough = document.getElementById('mangle-modal-passthrough').checked;
  3037. const src = document.getElementById('mangle-modal-src').value.trim();
  3038. const dst = document.getElementById('mangle-modal-dst').value.trim();
  3039. const inIface = document.getElementById('mangle-modal-iniface').value;
  3040. let srclist = document.getElementById('mangle-modal-srclist')?.value || '';
  3041. if (srclist && document.getElementById('mangle-modal-srclist-inv')?.checked) {
  3042. srclist = '!' + srclist.replace(/^!/, '');
  3043. }
  3044. let dstlist = document.getElementById('mangle-modal-dstlist')?.value || '';
  3045. if (dstlist && document.getElementById('mangle-modal-dstlist-inv')?.checked) {
  3046. dstlist = '!' + dstlist.replace(/^!/, '');
  3047. }
  3048. let srcgeoip = document.getElementById('mangle-modal-srcgeoip')?.value || '';
  3049. if (srcgeoip && document.getElementById('mangle-modal-srcgeoip-inv')?.checked) {
  3050. srcgeoip = '!' + srcgeoip.replace(/^!/, '');
  3051. }
  3052. let dstgeoip = document.getElementById('mangle-modal-dstgeoip')?.value || '';
  3053. if (dstgeoip && document.getElementById('mangle-modal-dstgeoip-inv')?.checked) {
  3054. dstgeoip = '!' + dstgeoip.replace(/^!/, '');
  3055. }
  3056. const connmark = document.getElementById('mangle-modal-connmark').value.trim();
  3057. const comment = document.getElementById('mangle-modal-comment').value.trim();
  3058. const disabled = document.getElementById('mangle-modal-disabled').checked;
  3059. const payload = {
  3060. id,
  3061. chain,
  3062. action,
  3063. passthrough,
  3064. src_address: src,
  3065. dst_address: dst,
  3066. in_interface: inIface,
  3067. src_address_list: srclist,
  3068. dst_address_list: dstlist,
  3069. src_geoip: srcgeoip,
  3070. dst_geoip: dstgeoip,
  3071. connection_mark: connmark,
  3072. comment,
  3073. disabled
  3074. };
  3075. if (action === 'mark-connection') payload.new_connection_mark = newmark;
  3076. else if (action === 'mark-routing') payload.new_routing_mark = newmark;
  3077. else if (action === 'mark-packet') payload.new_packet_mark = newmark;
  3078. else if (action === 'change-mss') payload.new_mss = newmark || 'clamp-to-pmtu';
  3079. try {
  3080. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  3081. method: 'POST',
  3082. headers: { 'Content-Type': 'application/json' },
  3083. body: JSON.stringify(payload)
  3084. });
  3085. if (res.ok) {
  3086. showToast('Mangle Rule Saved', 'Marking rule applied', 'success');
  3087. closeMangleModal();
  3088. loadFirewall(false);
  3089. }
  3090. } catch (err) {
  3091. showToast('Error', err.message, 'error');
  3092. }
  3093. }
  3094. async function moveMangleRule(id, dir) {
  3095. try {
  3096. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  3097. method: 'POST',
  3098. headers: { 'Content-Type': 'application/json' },
  3099. body: JSON.stringify({ direction: dir })
  3100. });
  3101. if (res.ok) loadFirewall(false);
  3102. } catch (err) {
  3103. showToast('Error', err.message, 'error');
  3104. }
  3105. }
  3106. async function toggleMangleRuleState(id, disabled) {
  3107. try {
  3108. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  3109. method: 'POST',
  3110. headers: { 'Content-Type': 'application/json' },
  3111. body: JSON.stringify({ disabled })
  3112. });
  3113. if (res.ok) loadFirewall(false);
  3114. } catch (err) {
  3115. showToast('Error', err.message, 'error');
  3116. }
  3117. }
  3118. async function deleteMangleRule(id) {
  3119. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  3120. try {
  3121. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3122. if (res.ok) {
  3123. showToast('Deleted', 'Mangle rule removed', 'success');
  3124. loadFirewall(false);
  3125. }
  3126. } catch (err) {
  3127. showToast('Error', err.message, 'error');
  3128. }
  3129. }
  3130. // ----------------- Address Lists -----------------
  3131. function renderAddressLists() {
  3132. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  3133. const tbody = document.getElementById('addrlist-table-body');
  3134. const empty = document.getElementById('addrlist-empty');
  3135. if (!tbody) return;
  3136. tbody.innerHTML = '';
  3137. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  3138. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries`;
  3139. // Update filter select
  3140. const sel = document.getElementById('addrlist-filter-name');
  3141. if (sel) {
  3142. const cur = sel.value;
  3143. sel.innerHTML = '<option value="">All Lists</option>';
  3144. const set = new Set((state.addressLists || []).map(a => a.name));
  3145. set.forEach(n => {
  3146. const opt = document.createElement('option');
  3147. opt.value = n;
  3148. opt.innerText = n;
  3149. if (n === cur) opt.selected = true;
  3150. sel.appendChild(opt);
  3151. });
  3152. }
  3153. if (entries.length === 0) {
  3154. empty?.classList.remove('hidden');
  3155. return;
  3156. }
  3157. empty?.classList.add('hidden');
  3158. entries.forEach((e, idx) => {
  3159. const tr = document.createElement('tr');
  3160. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
  3161. tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
  3162. tr.innerHTML = `
  3163. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  3164. <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>
  3165. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  3166. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  3167. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]">${e.comment || '-'}</td>
  3168. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  3169. <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>
  3170. <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
  3171. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3172. </td>
  3173. `;
  3174. tbody.appendChild(tr);
  3175. });
  3176. }
  3177. function openAddAddrListModal() {
  3178. document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
  3179. document.getElementById('addrlist-modal-id').value = '';
  3180. document.getElementById('addrlist-modal-name').value = '';
  3181. document.getElementById('addrlist-modal-addr').value = '';
  3182. document.getElementById('addrlist-modal-comment').value = '';
  3183. document.getElementById('addrlist-modal-disabled').checked = false;
  3184. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  3185. if (submitBtn) submitBtn.innerText = 'Add to List';
  3186. document.getElementById('addrlist-modal').classList.remove('hidden');
  3187. }
  3188. function openEditAddrListModal(id) {
  3189. const e = (state.addressLists || []).find(item => item.id === id);
  3190. if (!e) return;
  3191. document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
  3192. document.getElementById('addrlist-modal-id').value = e.id;
  3193. document.getElementById('addrlist-modal-name').value = e.name;
  3194. document.getElementById('addrlist-modal-addr').value = e.address;
  3195. document.getElementById('addrlist-modal-comment').value = e.comment || '';
  3196. document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
  3197. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  3198. if (submitBtn) submitBtn.innerText = 'Save Changes';
  3199. document.getElementById('addrlist-modal').classList.remove('hidden');
  3200. }
  3201. function closeAddrListModal() {
  3202. document.getElementById('addrlist-modal').classList.add('hidden');
  3203. }
  3204. async function submitSaveAddrList(e) {
  3205. e.preventDefault();
  3206. const id = document.getElementById('addrlist-modal-id').value;
  3207. const name = document.getElementById('addrlist-modal-name').value.trim();
  3208. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  3209. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  3210. const disabled = document.getElementById('addrlist-modal-disabled').checked;
  3211. try {
  3212. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  3213. method: 'POST',
  3214. headers: { 'Content-Type': 'application/json' },
  3215. body: JSON.stringify({ id, name, address: addr, comment, disabled })
  3216. });
  3217. if (res.ok) {
  3218. showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
  3219. closeAddrListModal();
  3220. loadFirewall(false);
  3221. } else {
  3222. const err = await res.json();
  3223. showToast('Error', err.message || 'Failed to save address list', 'error');
  3224. }
  3225. } catch (err) {
  3226. showToast('Error', err.message, 'error');
  3227. }
  3228. }
  3229. async function toggleAddrListState(id, disabled) {
  3230. try {
  3231. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
  3232. method: 'POST',
  3233. headers: { 'Content-Type': 'application/json' },
  3234. body: JSON.stringify({ disabled })
  3235. });
  3236. if (res.ok) {
  3237. loadFirewall(false);
  3238. }
  3239. } catch (err) {
  3240. showToast('Error', err.message, 'error');
  3241. }
  3242. }
  3243. async function deleteAddrList(id) {
  3244. if (!confirm('Are you sure you want to delete this address list item?')) return;
  3245. try {
  3246. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3247. if (res.ok) {
  3248. showToast('Deleted', 'Address list item removed', 'info');
  3249. loadFirewall(false);
  3250. }
  3251. } catch (err) {
  3252. showToast('Error', err.message, 'error');
  3253. }
  3254. }
  3255. // ----------------- Geo-Location IP Management -----------------
  3256. async function loadGeoIP() {
  3257. try {
  3258. const [statusRes, countriesRes] = await Promise.all([
  3259. fetch(`${API_BASE}/firewall/geoip/status`),
  3260. fetch(`${API_BASE}/firewall/geoip/countries`)
  3261. ]);
  3262. if (statusRes.ok) state.geoStatus = await statusRes.json();
  3263. if (countriesRes.ok) state.geoCountries = await countriesRes.json();
  3264. updateGeoHeader();
  3265. renderGeoCountries();
  3266. } catch (err) {
  3267. console.error('Failed to load GeoIP:', err);
  3268. }
  3269. }
  3270. function getGeoUsageMap() {
  3271. const usage = {};
  3272. const checkRule = (r, type) => {
  3273. ['src_geoip', 'dst_geoip'].forEach(field => {
  3274. let val = (r && r[field]) || '';
  3275. let code = val.replace(/^!/, '').replace(/^geo:/, '').replace(/^geo_/, '').toUpperCase().trim();
  3276. if (code) {
  3277. if (!usage[code]) usage[code] = [];
  3278. const label = `${type} #${r.priority !== undefined ? r.priority : (r.id || '')}`;
  3279. if (!usage[code].includes(label)) usage[code].push(label);
  3280. }
  3281. });
  3282. };
  3283. (state.filterRules || []).forEach(r => checkRule(r, 'Filter'));
  3284. (state.natRules || []).forEach(r => checkRule(r, 'NAT'));
  3285. (state.mangleRules || []).forEach(r => checkRule(r, 'Mangle'));
  3286. return usage;
  3287. }
  3288. function updateGeoHeader() {
  3289. const s = state.geoStatus || {};
  3290. const statusBadge = document.getElementById('geo-status-badge');
  3291. if (statusBadge) {
  3292. statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
  3293. statusBadge.className = s.auto_update
  3294. ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
  3295. : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
  3296. }
  3297. const intervalLabel = document.getElementById('geo-interval-label');
  3298. if (intervalLabel) {
  3299. intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
  3300. }
  3301. const usageMap = getGeoUsageMap();
  3302. const inUseCount = Object.keys(usageMap).length;
  3303. const activeCountEl = document.getElementById('geo-stat-active-countries');
  3304. if (activeCountEl) activeCountEl.innerText = inUseCount.toLocaleString();
  3305. const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
  3306. if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
  3307. const lastSyncEl = document.getElementById('geo-stat-last-sync');
  3308. if (lastSyncEl) {
  3309. if (s.last_updated && !s.last_updated.startsWith('0001')) {
  3310. const d = new Date(s.last_updated);
  3311. lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  3312. } else {
  3313. lastSyncEl.innerText = 'Never (Sync Pending)';
  3314. }
  3315. }
  3316. const nextSyncEl = document.getElementById('geo-stat-next-sync');
  3317. if (nextSyncEl) {
  3318. if (s.next_update && !s.next_update.startsWith('0001')) {
  3319. const d = new Date(s.next_update);
  3320. nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  3321. } else {
  3322. nextSyncEl.innerText = '-';
  3323. }
  3324. }
  3325. const badge = document.getElementById('fw-badge-geo');
  3326. if (badge) badge.innerText = inUseCount || (state.geoCountries || []).filter(c => c.subnet_count > 0).length || 0;
  3327. }
  3328. function renderGeoCountries() {
  3329. const tbody = document.getElementById('geo-table-body');
  3330. const empty = document.getElementById('geo-empty');
  3331. if (!tbody) return;
  3332. tbody.innerHTML = '';
  3333. const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
  3334. const continent = document.getElementById('geo-continent-filter')?.value || '';
  3335. const inUseOnly = document.getElementById('geo-filter-inuse-only')?.checked;
  3336. const cachedOnly = document.getElementById('geo-filter-cached-only')?.checked;
  3337. const usageMap = getGeoUsageMap();
  3338. const countries = (state.geoCountries || []).filter(c => {
  3339. const isUsed = !!usageMap[c.code];
  3340. if (inUseOnly && !isUsed) return false;
  3341. if (cachedOnly && (!c.subnet_count || c.subnet_count === 0)) return false;
  3342. if (continent && c.continent !== continent) return false;
  3343. if (q) {
  3344. const matchCode = c.code.toLowerCase().includes(q);
  3345. const matchName = c.name.toLowerCase().includes(q);
  3346. if (!matchCode && !matchName) return false;
  3347. }
  3348. return true;
  3349. });
  3350. if (countries.length === 0) {
  3351. empty?.classList.remove('hidden');
  3352. return;
  3353. }
  3354. empty?.classList.add('hidden');
  3355. countries.forEach(c => {
  3356. const tr = document.createElement('tr');
  3357. const isUsed = !!usageMap[c.code];
  3358. const rulesUsing = usageMap[c.code] || [];
  3359. tr.className = `hover:bg-slate-800/40 transition text-xs ${isUsed ? 'bg-emerald-950/20' : ''}`;
  3360. let statusHtml = '';
  3361. if (isUsed) {
  3362. 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>`;
  3363. } else if (c.subnet_count > 0) {
  3364. 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>';
  3365. } else {
  3366. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-slate-500 bg-slate-800/60">READY</span>';
  3367. }
  3368. tr.innerHTML = `
  3369. <td class="py-2.5 px-3 text-center">
  3370. <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'}">
  3371. ${c.code}
  3372. </span>
  3373. </td>
  3374. <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
  3375. <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
  3376. <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
  3377. ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
  3378. </td>
  3379. <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
  3380. <td class="py-2.5 px-3">
  3381. ${statusHtml}
  3382. </td>
  3383. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  3384. <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>
  3385. <button onclick="viewGeoSubnets('${c.code}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
  3386. </td>
  3387. `;
  3388. tbody.appendChild(tr);
  3389. });
  3390. }
  3391. function quickFilterGeo(preset) {
  3392. const searchInput = document.getElementById('geo-search-input');
  3393. const continentSel = document.getElementById('geo-continent-filter');
  3394. const inUseCheck = document.getElementById('geo-filter-inuse-only');
  3395. const cachedCheck = document.getElementById('geo-filter-cached-only');
  3396. if (searchInput) searchInput.value = '';
  3397. if (continentSel) continentSel.value = '';
  3398. if (inUseCheck) inUseCheck.checked = false;
  3399. if (cachedCheck) cachedCheck.checked = false;
  3400. if (preset === 'GR') {
  3401. if (searchInput) searchInput.value = 'Greece';
  3402. } else if (preset === 'Europe') {
  3403. if (continentSel) continentSel.value = 'Europe';
  3404. } else if (preset === 'HIGHRISK') {
  3405. if (searchInput) searchInput.value = 'China';
  3406. }
  3407. renderGeoCountries();
  3408. }
  3409. async function toggleGeoCountry(code, enabled) {
  3410. try {
  3411. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
  3412. method: 'POST',
  3413. headers: { 'Content-Type': 'application/json' },
  3414. body: JSON.stringify({ enabled })
  3415. });
  3416. if (res.ok) {
  3417. showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
  3418. loadGeoIP();
  3419. } else {
  3420. const err = await res.json();
  3421. showToast('Error', err.message || 'Failed to toggle country', 'error');
  3422. }
  3423. } catch (err) {
  3424. showToast('Error', err.message, 'error');
  3425. }
  3426. }
  3427. async function updateGeoCountry(code) {
  3428. try {
  3429. showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
  3430. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
  3431. if (res.ok) {
  3432. const data = await res.json();
  3433. showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
  3434. loadGeoIP();
  3435. } else {
  3436. const err = await res.json();
  3437. showToast('Sync Error', err.message || 'Failed to sync country', 'error');
  3438. }
  3439. } catch (err) {
  3440. showToast('Error', err.message, 'error');
  3441. }
  3442. }
  3443. async function triggerGeoUpdateNow() {
  3444. const spinner = document.getElementById('geo-update-spinner');
  3445. if (spinner) spinner.classList.remove('hidden');
  3446. try {
  3447. const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
  3448. if (res.ok) {
  3449. showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
  3450. setTimeout(() => {
  3451. loadGeoIP();
  3452. if (spinner) spinner.classList.add('hidden');
  3453. }, 2500);
  3454. } else {
  3455. const err = await res.json();
  3456. showToast('Notice', err.message || 'Update in progress', 'info');
  3457. if (spinner) spinner.classList.add('hidden');
  3458. }
  3459. } catch (err) {
  3460. showToast('Error', err.message, 'error');
  3461. if (spinner) spinner.classList.add('hidden');
  3462. }
  3463. }
  3464. async function applyGeoPreset(preset) {
  3465. try {
  3466. const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
  3467. method: 'POST',
  3468. headers: { 'Content-Type': 'application/json' },
  3469. body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
  3470. });
  3471. if (res.ok) {
  3472. showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
  3473. loadGeoIP();
  3474. }
  3475. } catch (err) {
  3476. showToast('Error', err.message, 'error');
  3477. }
  3478. }
  3479. function openGeoIntervalModal() {
  3480. const s = state.geoStatus || {};
  3481. document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
  3482. const sel = document.getElementById('geo-cfg-interval');
  3483. const customBox = document.getElementById('geo-cfg-custom-box');
  3484. const customHoursInput = document.getElementById('geo-cfg-custom-hours');
  3485. const curHours = s.interval_hours || 24;
  3486. const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
  3487. if (matchOption) {
  3488. sel.value = String(curHours);
  3489. customBox.classList.add('hidden');
  3490. } else {
  3491. sel.value = 'custom';
  3492. customHoursInput.value = curHours;
  3493. customBox.classList.remove('hidden');
  3494. }
  3495. document.getElementById('geo-interval-modal').classList.remove('hidden');
  3496. }
  3497. function closeGeoIntervalModal() {
  3498. document.getElementById('geo-interval-modal').classList.add('hidden');
  3499. }
  3500. function toggleCustomGeoInterval() {
  3501. const val = document.getElementById('geo-cfg-interval').value;
  3502. const customBox = document.getElementById('geo-cfg-custom-box');
  3503. if (val === 'custom') {
  3504. customBox.classList.remove('hidden');
  3505. } else {
  3506. customBox.classList.add('hidden');
  3507. }
  3508. }
  3509. async function submitGeoIntervalSettings(e) {
  3510. e.preventDefault();
  3511. const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
  3512. const intervalVal = document.getElementById('geo-cfg-interval').value;
  3513. let hours = 24;
  3514. if (intervalVal === 'custom') {
  3515. hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
  3516. } else {
  3517. hours = parseInt(intervalVal, 10) || 24;
  3518. }
  3519. try {
  3520. const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
  3521. method: 'POST',
  3522. headers: { 'Content-Type': 'application/json' },
  3523. body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
  3524. });
  3525. if (res.ok) {
  3526. showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
  3527. closeGeoIntervalModal();
  3528. loadGeoIP();
  3529. } else {
  3530. const err = await res.json();
  3531. showToast('Error', err.message || 'Failed to save schedule', 'error');
  3532. }
  3533. } catch (err) {
  3534. showToast('Error', err.message, 'error');
  3535. }
  3536. }
  3537. async function viewGeoSubnets(code, name) {
  3538. if (!name) {
  3539. const found = (state.geoCountries || []).find(x => x.code === code);
  3540. name = found ? found.name : code;
  3541. }
  3542. document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
  3543. document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
  3544. const listEl = document.getElementById('geo-subnets-list');
  3545. listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
  3546. document.getElementById('geo-subnets-modal').classList.remove('hidden');
  3547. try {
  3548. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
  3549. if (res.ok) {
  3550. const data = await res.json();
  3551. const subnets = data.subnets || [];
  3552. if (subnets.length === 0) {
  3553. listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
  3554. } else {
  3555. listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
  3556. }
  3557. } else {
  3558. listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
  3559. }
  3560. } catch (err) {
  3561. listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
  3562. }
  3563. }
  3564. function closeGeoSubnetsModal() {
  3565. document.getElementById('geo-subnets-modal').classList.add('hidden');
  3566. }
  3567. // ----------------- Active Connections Tracking -----------------
  3568. async function loadConnections() {
  3569. try {
  3570. const res = await fetch(`${API_BASE}/firewall/connections`);
  3571. const data = await res.json();
  3572. state.connections = Array.isArray(data) ? data : [];
  3573. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  3574. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  3575. renderConnections();
  3576. } catch (err) {
  3577. console.error('Failed to load connections:', err);
  3578. }
  3579. }
  3580. function renderConnections() {
  3581. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  3582. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  3583. const tbody = document.getElementById('conns-table-body');
  3584. const empty = document.getElementById('conns-empty');
  3585. if (!tbody) return;
  3586. tbody.innerHTML = '';
  3587. const conns = (state.connections || []).filter(c => {
  3588. if (protoFilter && c.protocol !== protoFilter) return false;
  3589. if (search) {
  3590. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  3591. if (!line.includes(search)) return false;
  3592. }
  3593. return true;
  3594. });
  3595. if (conns.length === 0) {
  3596. empty?.classList.remove('hidden');
  3597. return;
  3598. }
  3599. empty?.classList.add('hidden');
  3600. conns.slice(0, 150).forEach(c => {
  3601. const tr = document.createElement('tr');
  3602. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  3603. let stateColor = 'text-slate-400';
  3604. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  3605. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  3606. tr.innerHTML = `
  3607. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  3608. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  3609. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  3610. <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>
  3611. <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>
  3612. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  3613. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  3614. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  3615. <td class="py-2.5 px-3 text-right font-sans">
  3616. <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>
  3617. </td>
  3618. `;
  3619. tbody.appendChild(tr);
  3620. });
  3621. }
  3622. async function killConnection(protocol, src, sport, dst, dport) {
  3623. try {
  3624. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  3625. method: 'POST',
  3626. headers: { 'Content-Type': 'application/json' },
  3627. body: JSON.stringify({ protocol, src, sport, dst, dport })
  3628. });
  3629. if (res.ok) {
  3630. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  3631. loadConnections();
  3632. }
  3633. } catch (err) {
  3634. showToast('Error', err.message, 'error');
  3635. }
  3636. }
  3637. async function resetFirewallCounters() {
  3638. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  3639. try {
  3640. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  3641. if (res.ok) {
  3642. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  3643. loadFirewall(false);
  3644. }
  3645. } catch (err) {
  3646. showToast('Error', err.message, 'error');
  3647. }
  3648. }
  3649. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  3650. function switchRoutesSubTab(tab) {
  3651. state.routesSubTab = tab;
  3652. const tabs = ['routes', 'rules', 'tables'];
  3653. tabs.forEach(t => {
  3654. const panel = document.getElementById(`routes-subtab-${t}`);
  3655. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  3656. if (panel) {
  3657. if (t === tab) panel.classList.remove('hidden');
  3658. else panel.classList.add('hidden');
  3659. }
  3660. if (btn) {
  3661. if (t === tab) {
  3662. 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';
  3663. } else {
  3664. 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';
  3665. }
  3666. }
  3667. });
  3668. }
  3669. async function loadRoutes() {
  3670. try {
  3671. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  3672. fetch(`${API_BASE}/routes`),
  3673. fetch(`${API_BASE}/routing/rules`),
  3674. fetch(`${API_BASE}/routing/tables`)
  3675. ]);
  3676. if (routesRes.ok) state.routes = await routesRes.json();
  3677. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  3678. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  3679. const bRoutes = document.getElementById('routes-badge-routes');
  3680. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  3681. const bRules = document.getElementById('routes-badge-rules');
  3682. if (bRules) bRules.innerText = (state.policyRules || []).length;
  3683. const bTables = document.getElementById('routes-badge-tables');
  3684. if (bTables) bTables.innerText = (state.routingTables || []).length;
  3685. const bRoutesCount = document.getElementById('badge-routes-count');
  3686. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  3687. renderRoutesList();
  3688. renderPolicyRules();
  3689. renderRoutingTables();
  3690. } catch (err) {
  3691. console.error('Failed to load routing:', err);
  3692. }
  3693. }
  3694. function renderRoutesList() {
  3695. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  3696. const tbody = document.getElementById('routes-table-body');
  3697. const empty = document.getElementById('routes-empty');
  3698. if (!tbody) return;
  3699. tbody.innerHTML = '';
  3700. // Update table filter select
  3701. const sel = document.getElementById('routes-filter-table');
  3702. if (sel) {
  3703. const cur = sel.value;
  3704. sel.innerHTML = '<option value="">All Tables</option>';
  3705. (state.routingTables || []).forEach(t => {
  3706. const opt = document.createElement('option');
  3707. opt.value = t.name;
  3708. opt.innerText = t.name;
  3709. if (t.name === cur) opt.selected = true;
  3710. sel.appendChild(opt);
  3711. });
  3712. }
  3713. const routes = (state.routes || []).filter(r => !tableFilter || r.routing_table === tableFilter);
  3714. document.getElementById('routes-count-badge').innerText = `${routes.length} Routes`;
  3715. if (routes.length === 0) {
  3716. empty?.classList.remove('hidden');
  3717. return;
  3718. }
  3719. empty?.classList.add('hidden');
  3720. routes.forEach(r => {
  3721. const tr = document.createElement('tr');
  3722. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  3723. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  3724. // MikroTik Flags string: D=Dynamic, A=Active, C=Connect, S=Static, X=Disabled
  3725. let flags = '';
  3726. if (r.dynamic) flags += 'D';
  3727. if (r.active) flags += 'A';
  3728. if (r.connect) flags += 'C';
  3729. if (r.static) flags += 'S';
  3730. if (r.disabled) flags += 'X';
  3731. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  3732. tr.innerHTML = `
  3733. <td class="py-2.5 px-3 text-center">
  3734. <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'}">
  3735. ${flags || '-'}
  3736. </span>
  3737. </td>
  3738. <td class="py-2.5 px-3 font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${r.dst_address}</td>
  3739. <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>
  3740. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  3741. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  3742. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  3743. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  3744. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  3745. ${r.static ? `
  3746. <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>
  3747. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  3748. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3749. ` : `
  3750. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  3751. `}
  3752. </td>
  3753. `;
  3754. tbody.appendChild(tr);
  3755. });
  3756. }
  3757. function openAddRouteModal() {
  3758. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  3759. document.getElementById('route-modal-id').value = '';
  3760. document.getElementById('route-modal-old-dst').value = '';
  3761. document.getElementById('route-modal-old-gw').value = '';
  3762. document.getElementById('route-modal-old-distance').value = '';
  3763. document.getElementById('route-modal-old-table').value = '';
  3764. document.getElementById('route-modal-old-iface').value = '';
  3765. const dstInput = document.getElementById('route-modal-dst');
  3766. const gwInput = document.getElementById('route-modal-gw');
  3767. const distInput = document.getElementById('route-modal-distance');
  3768. const ifaceSelect = document.getElementById('route-modal-iface');
  3769. const tableSelect = document.getElementById('route-modal-table');
  3770. const commentInput = document.getElementById('route-modal-comment');
  3771. const disCheck = document.getElementById('route-modal-disabled');
  3772. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  3773. dstInput.disabled = false;
  3774. dstInput.value = '0.0.0.0/0';
  3775. gwInput.disabled = false;
  3776. gwInput.value = '';
  3777. distInput.disabled = false;
  3778. distInput.value = '1';
  3779. ifaceSelect.disabled = false;
  3780. tableSelect.disabled = false;
  3781. commentInput.disabled = false;
  3782. commentInput.value = '';
  3783. disCheck.disabled = false;
  3784. disCheck.checked = false;
  3785. if (saveBtn) saveBtn.classList.remove('hidden');
  3786. populateInterfaceSelect('route-modal-iface');
  3787. // Populate tables
  3788. tableSelect.innerHTML = '';
  3789. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  3790. const opt = document.createElement('option');
  3791. opt.value = t.name;
  3792. opt.innerText = t.name;
  3793. if (t.name === 'main') opt.selected = true;
  3794. tableSelect.appendChild(opt);
  3795. });
  3796. document.getElementById('route-modal').classList.remove('hidden');
  3797. }
  3798. function openEditRouteModal(id) {
  3799. const r = (state.routes || []).find(route => route.id === id);
  3800. if (!r) return;
  3801. const isStatic = !!r.static;
  3802. document.getElementById('route-modal-title').innerText = isStatic
  3803. ? `Edit Route: ${r.dst_address}`
  3804. : `Route Properties (Read Only): ${r.dst_address}`;
  3805. document.getElementById('route-modal-id').value = r.id;
  3806. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  3807. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  3808. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  3809. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  3810. document.getElementById('route-modal-old-iface').value = r.interface || '';
  3811. const dstInput = document.getElementById('route-modal-dst');
  3812. const gwInput = document.getElementById('route-modal-gw');
  3813. const distInput = document.getElementById('route-modal-distance');
  3814. const ifaceSelect = document.getElementById('route-modal-iface');
  3815. const tableSelect = document.getElementById('route-modal-table');
  3816. const commentInput = document.getElementById('route-modal-comment');
  3817. const disCheck = document.getElementById('route-modal-disabled');
  3818. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  3819. dstInput.value = r.dst_address;
  3820. gwInput.value = r.gateway || '';
  3821. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  3822. commentInput.value = r.comment || '';
  3823. disCheck.checked = !!r.disabled;
  3824. dstInput.disabled = !isStatic;
  3825. gwInput.disabled = !isStatic;
  3826. distInput.disabled = !isStatic;
  3827. ifaceSelect.disabled = !isStatic;
  3828. tableSelect.disabled = !isStatic;
  3829. commentInput.disabled = !isStatic;
  3830. disCheck.disabled = !isStatic;
  3831. if (saveBtn) {
  3832. if (isStatic) {
  3833. saveBtn.classList.remove('hidden');
  3834. } else {
  3835. saveBtn.classList.add('hidden');
  3836. }
  3837. }
  3838. populateInterfaceSelect('route-modal-iface', r.interface);
  3839. tableSelect.innerHTML = '';
  3840. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  3841. const opt = document.createElement('option');
  3842. opt.value = t.name;
  3843. opt.innerText = t.name;
  3844. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  3845. tableSelect.appendChild(opt);
  3846. });
  3847. document.getElementById('route-modal').classList.remove('hidden');
  3848. }
  3849. function closeRouteModal() {
  3850. document.getElementById('route-modal').classList.add('hidden');
  3851. }
  3852. async function submitSaveRoute(e) {
  3853. e.preventDefault();
  3854. const id = document.getElementById('route-modal-id').value;
  3855. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  3856. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  3857. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  3858. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  3859. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  3860. const dst = document.getElementById('route-modal-dst').value.trim();
  3861. const gw = document.getElementById('route-modal-gw').value.trim();
  3862. const table = document.getElementById('route-modal-table').value;
  3863. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  3864. const iface = document.getElementById('route-modal-iface').value;
  3865. const comment = document.getElementById('route-modal-comment').value.trim();
  3866. const disabled = document.getElementById('route-modal-disabled').checked;
  3867. if (!dst) {
  3868. showToast('Error', 'Destination address is required', 'error');
  3869. return;
  3870. }
  3871. if (!gw && !iface) {
  3872. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  3873. return;
  3874. }
  3875. const payload = {
  3876. id,
  3877. old_dst_address: oldDst,
  3878. old_gateway: oldGw,
  3879. old_routing_table: oldTable,
  3880. old_interface: oldIface,
  3881. dst_address: dst,
  3882. gateway: gw || iface,
  3883. routing_table: table,
  3884. distance,
  3885. interface: iface,
  3886. comment,
  3887. disabled
  3888. };
  3889. if (oldDistStr !== undefined && oldDistStr !== '') {
  3890. payload.old_distance = parseInt(oldDistStr, 10);
  3891. }
  3892. try {
  3893. const res = await fetch(`${API_BASE}/routes`, {
  3894. method: 'POST',
  3895. headers: { 'Content-Type': 'application/json' },
  3896. body: JSON.stringify(payload)
  3897. });
  3898. if (res.ok) {
  3899. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  3900. closeRouteModal();
  3901. loadRoutes();
  3902. } else {
  3903. const err = await res.json();
  3904. showToast('Error', err.message || 'Failed to save route', 'error');
  3905. }
  3906. } catch (err) {
  3907. showToast('Error', err.message, 'error');
  3908. }
  3909. }
  3910. async function toggleRouteState(id, disabled) {
  3911. try {
  3912. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  3913. method: 'POST',
  3914. headers: { 'Content-Type': 'application/json' },
  3915. body: JSON.stringify({ disabled })
  3916. });
  3917. if (res.ok) loadRoutes();
  3918. } catch (err) {
  3919. showToast('Error', err.message, 'error');
  3920. }
  3921. }
  3922. async function deleteRoute(id) {
  3923. if (!confirm('Are you sure you want to delete this route?')) return;
  3924. try {
  3925. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3926. if (res.ok) {
  3927. showToast('Deleted', 'Route removed', 'success');
  3928. loadRoutes();
  3929. }
  3930. } catch (err) {
  3931. showToast('Error', err.message, 'error');
  3932. }
  3933. }
  3934. // ----------------- Policy Rules (/ip route rule) -----------------
  3935. function renderPolicyRules() {
  3936. const tbody = document.getElementById('rules-table-body');
  3937. const empty = document.getElementById('rules-empty');
  3938. if (!tbody) return;
  3939. tbody.innerHTML = '';
  3940. const rules = state.policyRules || [];
  3941. document.getElementById('rules-count-badge').innerText = `${rules.length} Rules`;
  3942. if (rules.length === 0) {
  3943. empty?.classList.remove('hidden');
  3944. return;
  3945. }
  3946. empty?.classList.add('hidden');
  3947. rules.forEach(pr => {
  3948. const tr = document.createElement('tr');
  3949. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  3950. tr.innerHTML = `
  3951. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  3952. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  3953. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  3954. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  3955. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  3956. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  3957. <td class="py-2.5 px-3 text-right font-sans">
  3958. ${pr.priority < 32766 && pr.priority > 0 ? `
  3959. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3960. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  3961. </td>
  3962. `;
  3963. tbody.appendChild(tr);
  3964. });
  3965. }
  3966. function openAddPolicyRuleModal() {
  3967. document.getElementById('prule-modal-pref').value = (state.policyRules || []).length * 10 + 1000;
  3968. document.getElementById('prule-modal-mark').value = '';
  3969. document.getElementById('prule-modal-src').value = '';
  3970. document.getElementById('prule-modal-dst').value = '';
  3971. const sel = document.getElementById('prule-modal-table');
  3972. sel.innerHTML = '';
  3973. (state.routingTables || []).forEach(t => {
  3974. const opt = document.createElement('option');
  3975. opt.value = t.name;
  3976. opt.innerText = t.name;
  3977. sel.appendChild(opt);
  3978. });
  3979. document.getElementById('prule-modal').classList.remove('hidden');
  3980. }
  3981. function closePolicyRuleModal() {
  3982. document.getElementById('prule-modal').classList.add('hidden');
  3983. }
  3984. async function submitSavePolicyRule(e) {
  3985. e.preventDefault();
  3986. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  3987. const mark = document.getElementById('prule-modal-mark').value.trim();
  3988. const src = document.getElementById('prule-modal-src').value.trim();
  3989. const dst = document.getElementById('prule-modal-dst').value.trim();
  3990. const table = document.getElementById('prule-modal-table').value;
  3991. const action = document.getElementById('prule-modal-action').value;
  3992. try {
  3993. const res = await fetch(`${API_BASE}/routing/rules`, {
  3994. method: 'POST',
  3995. headers: { 'Content-Type': 'application/json' },
  3996. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  3997. });
  3998. if (res.ok) {
  3999. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  4000. closePolicyRuleModal();
  4001. loadRoutes();
  4002. } else {
  4003. const err = await res.json();
  4004. showToast('Error', err.message, 'error');
  4005. }
  4006. } catch (err) {
  4007. showToast('Error', err.message, 'error');
  4008. }
  4009. }
  4010. async function deletePolicyRule(id) {
  4011. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  4012. try {
  4013. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4014. if (res.ok) {
  4015. showToast('Rule Removed', 'Policy rule deleted', 'success');
  4016. loadRoutes();
  4017. }
  4018. } catch (err) {
  4019. showToast('Error', err.message, 'error');
  4020. }
  4021. }
  4022. // ----------------- Routing Tables -----------------
  4023. function renderRoutingTables() {
  4024. const tbody = document.getElementById('tables-table-body');
  4025. if (!tbody) return;
  4026. tbody.innerHTML = '';
  4027. (state.routingTables || []).forEach(t => {
  4028. const tr = document.createElement('tr');
  4029. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  4030. tr.innerHTML = `
  4031. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  4032. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  4033. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  4034. `;
  4035. tbody.appendChild(tr);
  4036. });
  4037. }
  4038. function openAddTableModal() {
  4039. document.getElementById('table-modal-name').value = '';
  4040. document.getElementById('table-modal-id').value = '';
  4041. document.getElementById('table-modal-comment').value = '';
  4042. document.getElementById('table-modal').classList.remove('hidden');
  4043. }
  4044. function closeTableModal() {
  4045. document.getElementById('table-modal').classList.add('hidden');
  4046. }
  4047. async function submitSaveTable(e) {
  4048. e.preventDefault();
  4049. const name = document.getElementById('table-modal-name').value.trim();
  4050. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  4051. const comment = document.getElementById('table-modal-comment').value.trim();
  4052. try {
  4053. const res = await fetch(`${API_BASE}/routing/tables`, {
  4054. method: 'POST',
  4055. headers: { 'Content-Type': 'application/json' },
  4056. body: JSON.stringify({ name, table_id: id, comment })
  4057. });
  4058. if (res.ok) {
  4059. showToast('Table Created', `Routing table ${name} registered`, 'success');
  4060. closeTableModal();
  4061. loadRoutes();
  4062. } else {
  4063. const err = await res.json();
  4064. showToast('Error', err.message, 'error');
  4065. }
  4066. } catch (err) {
  4067. showToast('Error', err.message, 'error');
  4068. }
  4069. }
  4070. async function loadDebianConfig() {
  4071. const view = document.getElementById('debian-config-view');
  4072. view.innerText = 'Generating live configuration...';
  4073. try {
  4074. const res = await fetch(`${API_BASE}/debian/config`);
  4075. const data = await res.json();
  4076. view.innerText = data.content || '# Empty config';
  4077. } catch (err) {
  4078. view.innerText = 'Failed to generate Debian network config.';
  4079. }
  4080. }
  4081. async function saveDebianConfig() {
  4082. try {
  4083. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  4084. const data = await res.json();
  4085. if (res.ok) {
  4086. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  4087. loadDebianConfig();
  4088. }
  4089. } catch (err) {
  4090. showToast('Error', err.message, 'error');
  4091. }
  4092. }
  4093. function showToast(title, message, type = 'info') {
  4094. const container = document.getElementById('toast-container');
  4095. const toast = document.createElement('div');
  4096. const borderColors = {
  4097. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  4098. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  4099. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  4100. };
  4101. 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}`;
  4102. toast.innerHTML = `
  4103. <div class="flex-1">
  4104. <div class="font-bold text-xs text-white">${title}</div>
  4105. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${message}</div>
  4106. </div>
  4107. `;
  4108. container.appendChild(toast);
  4109. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  4110. setTimeout(() => {
  4111. toast.classList.add('opacity-0', 'translate-y-2');
  4112. setTimeout(() => toast.remove(), 300);
  4113. }, 4000);
  4114. }
  4115. function formatTraffic(bytesPerSec) {
  4116. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  4117. const kb = bytesPerSec / 1024;
  4118. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  4119. const mb = kb / 1024;
  4120. return `${mb.toFixed(2)} MB/s`;
  4121. }
  4122. function toggleSidebar() {
  4123. const sb = document.getElementById('sidebar');
  4124. sb.classList.toggle('-translate-x-full');
  4125. }
  4126. // ======================== EoIP (Ethernet over IP) ========================
  4127. async function loadEoIP(populate = true) {
  4128. try {
  4129. const res = await fetch(`${API_BASE}/vpn/eoip`);
  4130. const data = await res.json();
  4131. state.eoipTunnels = Array.isArray(data) ? data : [];
  4132. const badge = document.getElementById('eoip-count-badge');
  4133. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  4134. const sideBadge = document.getElementById('badge-eoip-count');
  4135. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  4136. renderEoIPTunnels();
  4137. } catch (err) {
  4138. console.error('Failed to load EoIP:', err);
  4139. }
  4140. }
  4141. function renderEoIPTunnels() {
  4142. const tbody = document.getElementById('eoip-table-body');
  4143. const empty = document.getElementById('eoip-empty');
  4144. if (!tbody) return;
  4145. tbody.innerHTML = '';
  4146. const tunnels = state.eoipTunnels || [];
  4147. if (tunnels.length === 0) {
  4148. empty?.classList.remove('hidden');
  4149. return;
  4150. }
  4151. empty?.classList.add('hidden');
  4152. tunnels.forEach(t => {
  4153. const tr = document.createElement('tr');
  4154. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  4155. tr.innerHTML = `
  4156. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  4157. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  4158. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  4159. <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>
  4160. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  4161. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  4162. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  4163. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  4164. <td class="py-2.5 px-3 font-mono text-[11px]">
  4165. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  4166. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  4167. </td>
  4168. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  4169. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4170. <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>
  4171. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4172. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  4173. </td>
  4174. `;
  4175. tbody.appendChild(tr);
  4176. });
  4177. }
  4178. function openAddEoIPModal() {
  4179. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  4180. document.getElementById('eoip-modal-id').value = '';
  4181. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  4182. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  4183. document.getElementById('eoip-modal-remote').value = '';
  4184. document.getElementById('eoip-modal-ip').value = '';
  4185. document.getElementById('eoip-modal-local').value = '';
  4186. document.getElementById('eoip-modal-mac').value = '';
  4187. document.getElementById('eoip-modal-mtu').value = '1500';
  4188. document.getElementById('eoip-modal-comment').value = '';
  4189. document.getElementById('eoip-modal-clampmss').checked = true;
  4190. document.getElementById('eoip-modal-disabled').checked = false;
  4191. document.getElementById('eoip-modal').classList.remove('hidden');
  4192. }
  4193. function openEditEoIPModal(id) {
  4194. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  4195. if (!t) return;
  4196. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  4197. document.getElementById('eoip-modal-id').value = t.id;
  4198. document.getElementById('eoip-modal-name').value = t.name;
  4199. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  4200. document.getElementById('eoip-modal-remote').value = t.remote_address;
  4201. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  4202. document.getElementById('eoip-modal-local').value = t.local_address || '';
  4203. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  4204. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  4205. document.getElementById('eoip-modal-comment').value = t.comment || '';
  4206. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  4207. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  4208. document.getElementById('eoip-modal').classList.remove('hidden');
  4209. }
  4210. function closeEoIPModal() {
  4211. document.getElementById('eoip-modal').classList.add('hidden');
  4212. }
  4213. async function submitSaveEoIP(e) {
  4214. e.preventDefault();
  4215. const id = document.getElementById('eoip-modal-id').value;
  4216. const name = document.getElementById('eoip-modal-name').value.trim();
  4217. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  4218. const remote = document.getElementById('eoip-modal-remote').value.trim();
  4219. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  4220. const local = document.getElementById('eoip-modal-local').value.trim();
  4221. const mac = document.getElementById('eoip-modal-mac').value.trim();
  4222. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  4223. const comment = document.getElementById('eoip-modal-comment').value.trim();
  4224. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  4225. const disabled = document.getElementById('eoip-modal-disabled').checked;
  4226. try {
  4227. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  4228. method: 'POST',
  4229. headers: { 'Content-Type': 'application/json' },
  4230. body: JSON.stringify({
  4231. id,
  4232. name,
  4233. tunnel_id: tunnelId,
  4234. remote_address: remote,
  4235. ip_address: ipAddress,
  4236. local_address: local,
  4237. mac_address: mac,
  4238. mtu,
  4239. clamp_mss: clampMss,
  4240. comment,
  4241. disabled
  4242. })
  4243. });
  4244. if (res.ok) {
  4245. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  4246. closeEoIPModal();
  4247. loadEoIP(false);
  4248. fetchData(false);
  4249. } else {
  4250. const err = await res.json();
  4251. showToast('Error', err.message, 'error');
  4252. }
  4253. } catch (err) {
  4254. showToast('Error', err.message, 'error');
  4255. }
  4256. }
  4257. async function toggleEoIPState(id, disabled) {
  4258. try {
  4259. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  4260. method: 'POST',
  4261. headers: { 'Content-Type': 'application/json' },
  4262. body: JSON.stringify({ disabled })
  4263. });
  4264. if (res.ok) {
  4265. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  4266. loadEoIP(false);
  4267. fetchData(false);
  4268. }
  4269. } catch (err) {
  4270. showToast('Error', err.message, 'error');
  4271. }
  4272. }
  4273. async function deleteEoIP(id) {
  4274. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  4275. try {
  4276. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4277. if (res.ok) {
  4278. showToast('Deleted', 'EoIP tunnel removed', 'success');
  4279. loadEoIP(false);
  4280. fetchData(false);
  4281. }
  4282. } catch (err) {
  4283. showToast('Error', err.message, 'error');
  4284. }
  4285. }
  4286. // ======================== PPP Central Hub & Servers ========================
  4287. function switchPPPSubTab(tab) {
  4288. state.pppSubTab = tab;
  4289. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  4290. tabs.forEach(t => {
  4291. const panel = document.getElementById(`ppp-subtab-${t}`);
  4292. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  4293. if (panel) {
  4294. if (t === tab) panel.classList.remove('hidden');
  4295. else panel.classList.add('hidden');
  4296. }
  4297. if (btn) {
  4298. if (t === tab) {
  4299. 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';
  4300. } else {
  4301. 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';
  4302. }
  4303. }
  4304. });
  4305. const addBtn = document.getElementById('ppp-primary-add-btn');
  4306. if (addBtn) {
  4307. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  4308. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  4309. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  4310. else addBtn.innerHTML = '<span>Save Config</span>';
  4311. }
  4312. if (tab === 'active') loadPPPSessions();
  4313. }
  4314. function openCurrentPPPModal() {
  4315. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  4316. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  4317. else if (state.pppSubTab === 'active') loadPPPSessions();
  4318. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  4319. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  4320. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  4321. }
  4322. async function loadPPP(populateDropdowns = true) {
  4323. await Promise.all([
  4324. loadPPPSecrets(),
  4325. loadPPPProfiles(),
  4326. loadPPPServers(),
  4327. loadPPPSessions()
  4328. ]);
  4329. }
  4330. async function loadPPPSecrets() {
  4331. try {
  4332. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  4333. const data = await res.json();
  4334. state.pppSecrets = Array.isArray(data) ? data : [];
  4335. const b = document.getElementById('ppp-badge-secrets');
  4336. if (b) b.innerText = state.pppSecrets.length;
  4337. const b2 = document.getElementById('secrets-count-badge');
  4338. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  4339. renderPPPSecrets();
  4340. } catch (err) {
  4341. console.error('Failed to load PPP secrets:', err);
  4342. }
  4343. }
  4344. function renderPPPSecrets() {
  4345. const tbody = document.getElementById('secrets-table-body');
  4346. const empty = document.getElementById('secrets-empty');
  4347. if (!tbody) return;
  4348. tbody.innerHTML = '';
  4349. const secrets = state.pppSecrets || [];
  4350. if (secrets.length === 0) {
  4351. empty?.classList.remove('hidden');
  4352. return;
  4353. }
  4354. empty?.classList.add('hidden');
  4355. secrets.forEach(s => {
  4356. const tr = document.createElement('tr');
  4357. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  4358. tr.innerHTML = `
  4359. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  4360. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  4361. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  4362. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  4363. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  4364. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  4365. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  4366. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4367. <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>
  4368. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4369. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  4370. </td>
  4371. `;
  4372. tbody.appendChild(tr);
  4373. });
  4374. }
  4375. async function loadPPPProfiles() {
  4376. try {
  4377. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  4378. const data = await res.json();
  4379. state.pppProfiles = Array.isArray(data) ? data : [];
  4380. const b = document.getElementById('ppp-badge-profiles');
  4381. if (b) b.innerText = state.pppProfiles.length;
  4382. const b2 = document.getElementById('profiles-count-badge');
  4383. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  4384. // Populate profile selects across modals
  4385. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  4386. selects.forEach(sid => {
  4387. const el = document.getElementById(sid);
  4388. if (!el) return;
  4389. const cur = el.value;
  4390. el.innerHTML = '';
  4391. state.pppProfiles.forEach(p => {
  4392. const opt = document.createElement('option');
  4393. opt.value = p.name;
  4394. opt.innerText = `${p.name} (${p.remote_address})`;
  4395. if (p.name === cur) opt.selected = true;
  4396. el.appendChild(opt);
  4397. });
  4398. });
  4399. renderPPPProfiles();
  4400. } catch (err) {
  4401. console.error('Failed to load PPP profiles:', err);
  4402. }
  4403. }
  4404. function renderPPPProfiles() {
  4405. const tbody = document.getElementById('profiles-table-body');
  4406. if (!tbody) return;
  4407. tbody.innerHTML = '';
  4408. (state.pppProfiles || []).forEach(p => {
  4409. const isDefault = p.name.startsWith('default');
  4410. const tr = document.createElement('tr');
  4411. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  4412. tr.innerHTML = `
  4413. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  4414. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  4415. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  4416. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  4417. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  4418. <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>
  4419. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  4420. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  4421. ${!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>`}
  4422. </td>
  4423. `;
  4424. tbody.appendChild(tr);
  4425. });
  4426. }
  4427. async function loadPPPServers() {
  4428. try {
  4429. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  4430. fetch(`${API_BASE}/vpn/servers/pppoe`),
  4431. fetch(`${API_BASE}/vpn/servers/pptp`),
  4432. fetch(`${API_BASE}/vpn/servers/l2tp`),
  4433. fetch(`${API_BASE}/vpn/servers/ipsec`)
  4434. ]);
  4435. if (pppoeRes.ok) {
  4436. state.pppoeServer = await pppoeRes.json();
  4437. const s = state.pppoeServer;
  4438. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  4439. document.getElementById('pppoe-server-name').value = s.service_name || 'proxmox-pppoe';
  4440. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  4441. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  4442. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  4443. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  4444. const pill = document.getElementById('pppoe-server-status-pill');
  4445. if (pill) {
  4446. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  4447. 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';
  4448. }
  4449. setDotBadge('ppp-badge-pppoe-state', s.running);
  4450. }
  4451. if (pptpRes.ok) {
  4452. state.pptpServer = await pptpRes.json();
  4453. const s = state.pptpServer;
  4454. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  4455. document.getElementById('pptp-server-port').value = s.port || 1723;
  4456. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  4457. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  4458. const pill = document.getElementById('pptp-server-status-pill');
  4459. if (pill) {
  4460. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  4461. 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';
  4462. }
  4463. setDotBadge('ppp-badge-pptp-state', s.running);
  4464. }
  4465. if (l2tpRes.ok) {
  4466. state.l2tpServer = await l2tpRes.json();
  4467. const s = state.l2tpServer;
  4468. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  4469. document.getElementById('l2tp-server-port').value = s.port || 1701;
  4470. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  4471. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  4472. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  4473. const pill = document.getElementById('l2tp-server-status-pill');
  4474. if (pill) {
  4475. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  4476. 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';
  4477. }
  4478. setDotBadge('ppp-badge-l2tp-state', s.running);
  4479. }
  4480. if (ipsecRes.ok) {
  4481. state.ipsecServer = await ipsecRes.json();
  4482. const s = state.ipsecServer;
  4483. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  4484. if (modalEn) modalEn.checked = !!s.enabled;
  4485. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  4486. if (modalPsk) modalPsk.value = s.preshared_key || '';
  4487. const modalPool = document.getElementById('modal-ipsec-server-pool');
  4488. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  4489. const modalDns = document.getElementById('modal-ipsec-server-dns');
  4490. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  4491. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  4492. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  4493. const pill = document.getElementById('modal-ipsec-server-status');
  4494. if (pill) {
  4495. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  4496. 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';
  4497. }
  4498. }
  4499. } catch (err) {
  4500. console.error('Failed to load VPN servers:', err);
  4501. }
  4502. }
  4503. async function loadPPPSessions() {
  4504. try {
  4505. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  4506. const data = await res.json();
  4507. state.pppActiveSessions = Array.isArray(data) ? data : [];
  4508. const b = document.getElementById('ppp-badge-active');
  4509. if (b) b.innerText = state.pppActiveSessions.length;
  4510. const sideB = document.getElementById('badge-ppp-sessions');
  4511. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  4512. renderPPPSessions();
  4513. } catch (err) {
  4514. console.error('Failed to load active PPP sessions:', err);
  4515. }
  4516. }
  4517. function renderPPPSessions() {
  4518. const tbody = document.getElementById('active-ppp-table-body');
  4519. const empty = document.getElementById('active-ppp-empty');
  4520. if (!tbody) return;
  4521. tbody.innerHTML = '';
  4522. const list = state.pppActiveSessions || [];
  4523. if (list.length === 0) {
  4524. empty?.classList.remove('hidden');
  4525. return;
  4526. }
  4527. empty?.classList.add('hidden');
  4528. list.forEach(s => {
  4529. const tr = document.createElement('tr');
  4530. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  4531. tr.innerHTML = `
  4532. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  4533. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  4534. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  4535. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  4536. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  4537. <td class="py-2.5 px-3 text-[11px]">
  4538. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  4539. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  4540. </td>
  4541. <td class="py-2.5 px-3 text-right font-sans">
  4542. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  4543. </td>
  4544. `;
  4545. tbody.appendChild(tr);
  4546. });
  4547. }
  4548. async function disconnectPPPSession(iface) {
  4549. if (!confirm(`Disconnect session ${iface}?`)) return;
  4550. try {
  4551. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  4552. if (res.ok) {
  4553. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  4554. loadPPPSessions();
  4555. }
  4556. } catch (err) {
  4557. showToast('Error', err.message, 'error');
  4558. }
  4559. }
  4560. // PPP Secret Modal handlers
  4561. function openAddPPPSecretModal() {
  4562. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  4563. document.getElementById('secret-modal-id').value = '';
  4564. document.getElementById('secret-modal-name').value = '';
  4565. document.getElementById('secret-modal-password').value = '';
  4566. document.getElementById('secret-modal-service').value = 'any';
  4567. document.getElementById('secret-modal-profile').value = 'default';
  4568. document.getElementById('secret-modal-local').value = '';
  4569. document.getElementById('secret-modal-remote').value = '';
  4570. document.getElementById('secret-modal-comment').value = '';
  4571. document.getElementById('secret-modal-disabled').checked = false;
  4572. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  4573. }
  4574. function openEditPPPSecretModal(id) {
  4575. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  4576. if (!s) return;
  4577. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  4578. document.getElementById('secret-modal-id').value = s.id;
  4579. document.getElementById('secret-modal-name').value = s.name;
  4580. document.getElementById('secret-modal-password').value = s.password;
  4581. document.getElementById('secret-modal-service').value = s.service || 'any';
  4582. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  4583. document.getElementById('secret-modal-local').value = s.local_address || '';
  4584. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  4585. document.getElementById('secret-modal-comment').value = s.comment || '';
  4586. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  4587. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  4588. }
  4589. function closePPPSecretModal() {
  4590. document.getElementById('ppp-secret-modal').classList.add('hidden');
  4591. }
  4592. async function submitSavePPPSecret(e) {
  4593. e.preventDefault();
  4594. const id = document.getElementById('secret-modal-id').value;
  4595. const name = document.getElementById('secret-modal-name').value.trim();
  4596. const password = document.getElementById('secret-modal-password').value.trim();
  4597. const service = document.getElementById('secret-modal-service').value;
  4598. const profile = document.getElementById('secret-modal-profile').value;
  4599. const local = document.getElementById('secret-modal-local').value.trim();
  4600. const remote = document.getElementById('secret-modal-remote').value.trim();
  4601. const comment = document.getElementById('secret-modal-comment').value.trim();
  4602. const disabled = document.getElementById('secret-modal-disabled').checked;
  4603. try {
  4604. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  4605. method: 'POST',
  4606. headers: { 'Content-Type': 'application/json' },
  4607. body: JSON.stringify({
  4608. id,
  4609. name,
  4610. password,
  4611. service,
  4612. profile,
  4613. local_address: local,
  4614. remote_address: remote,
  4615. comment,
  4616. disabled
  4617. })
  4618. });
  4619. if (res.ok) {
  4620. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  4621. closePPPSecretModal();
  4622. loadPPPSecrets();
  4623. } else {
  4624. const err = await res.json();
  4625. showToast('Error', err.message, 'error');
  4626. }
  4627. } catch (err) {
  4628. showToast('Error', err.message, 'error');
  4629. }
  4630. }
  4631. async function togglePPPSecretState(id, disabled) {
  4632. try {
  4633. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  4634. method: 'POST',
  4635. headers: { 'Content-Type': 'application/json' },
  4636. body: JSON.stringify({ disabled })
  4637. });
  4638. if (res.ok) {
  4639. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  4640. loadPPPSecrets();
  4641. }
  4642. } catch (err) {
  4643. showToast('Error', err.message, 'error');
  4644. }
  4645. }
  4646. async function deletePPPSecret(id) {
  4647. if (!confirm('Are you sure you want to delete this secret account?')) return;
  4648. try {
  4649. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4650. if (res.ok) {
  4651. showToast('Deleted', 'Secret account removed', 'success');
  4652. loadPPPSecrets();
  4653. }
  4654. } catch (err) {
  4655. showToast('Error', err.message, 'error');
  4656. }
  4657. }
  4658. // PPP Profile Modal handlers
  4659. function openAddPPPProfileModal() {
  4660. document.getElementById('profile-modal-name').value = '';
  4661. document.getElementById('profile-modal-local').value = '10.10.10.1';
  4662. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  4663. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  4664. document.getElementById('profile-modal-encryption').value = 'required';
  4665. document.getElementById('profile-modal-onlyone').checked = true;
  4666. document.getElementById('profile-modal-comment').value = '';
  4667. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  4668. }
  4669. function closePPPProfileModal() {
  4670. document.getElementById('ppp-profile-modal').classList.add('hidden');
  4671. }
  4672. async function submitSavePPPProfile(e) {
  4673. e.preventDefault();
  4674. const name = document.getElementById('profile-modal-name').value.trim();
  4675. const local = document.getElementById('profile-modal-local').value.trim();
  4676. const remote = document.getElementById('profile-modal-remote').value.trim();
  4677. const dns = document.getElementById('profile-modal-dns').value.trim();
  4678. const enc = document.getElementById('profile-modal-encryption').value;
  4679. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  4680. const comment = document.getElementById('profile-modal-comment').value.trim();
  4681. try {
  4682. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  4683. method: 'POST',
  4684. headers: { 'Content-Type': 'application/json' },
  4685. body: JSON.stringify({
  4686. id: name,
  4687. name,
  4688. local_address: local,
  4689. remote_address: remote,
  4690. dns_servers: dns,
  4691. use_encryption: enc,
  4692. only_one: onlyone,
  4693. comment
  4694. })
  4695. });
  4696. if (res.ok) {
  4697. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  4698. closePPPProfileModal();
  4699. loadPPPProfiles();
  4700. } else {
  4701. const err = await res.json();
  4702. showToast('Error', err.message, 'error');
  4703. }
  4704. } catch (err) {
  4705. showToast('Error', err.message, 'error');
  4706. }
  4707. }
  4708. async function deletePPPProfile(name) {
  4709. if (!confirm(`Delete PPP profile ${name}?`)) return;
  4710. try {
  4711. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  4712. if (res.ok) {
  4713. showToast('Deleted', 'Profile removed', 'success');
  4714. loadPPPProfiles();
  4715. } else {
  4716. const err = await res.json();
  4717. showToast('Error', err.message, 'error');
  4718. }
  4719. } catch (err) {
  4720. showToast('Error', err.message, 'error');
  4721. }
  4722. }
  4723. // Server Config submissions
  4724. async function savePPPoEServerConfig(e) {
  4725. e.preventDefault();
  4726. const enabled = document.getElementById('pppoe-server-enabled').checked;
  4727. const name = document.getElementById('pppoe-server-name').value.trim();
  4728. const iface = document.getElementById('pppoe-server-iface').value;
  4729. const profile = document.getElementById('pppoe-server-profile').value;
  4730. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  4731. const onesession = document.getElementById('pppoe-server-onesession').checked;
  4732. try {
  4733. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  4734. method: 'POST',
  4735. headers: { 'Content-Type': 'application/json' },
  4736. body: JSON.stringify({
  4737. enabled,
  4738. service_name: name,
  4739. interface: iface,
  4740. default_profile: profile,
  4741. max_mtu: mtu,
  4742. max_mru: mtu,
  4743. one_session_per_host: onesession
  4744. })
  4745. });
  4746. if (res.ok) {
  4747. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  4748. loadPPPServers();
  4749. fetchData(false);
  4750. } else {
  4751. const err = await res.json();
  4752. showToast('Error', err.message, 'error');
  4753. }
  4754. } catch (err) {
  4755. showToast('Error', err.message, 'error');
  4756. }
  4757. }
  4758. async function savePPTPServerConfig(e) {
  4759. e.preventDefault();
  4760. const enabled = document.getElementById('pptp-server-enabled').checked;
  4761. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  4762. const profile = document.getElementById('pptp-server-profile').value;
  4763. const mppe = document.getElementById('pptp-server-mppe').checked;
  4764. try {
  4765. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  4766. method: 'POST',
  4767. headers: { 'Content-Type': 'application/json' },
  4768. body: JSON.stringify({
  4769. enabled,
  4770. port,
  4771. default_profile: profile,
  4772. require_mppe: mppe
  4773. })
  4774. });
  4775. if (res.ok) {
  4776. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  4777. loadPPPServers();
  4778. fetchData(false);
  4779. } else {
  4780. const err = await res.json();
  4781. showToast('Error', err.message, 'error');
  4782. }
  4783. } catch (err) {
  4784. showToast('Error', err.message, 'error');
  4785. }
  4786. }
  4787. async function saveL2TPServerConfig(e) {
  4788. e.preventDefault();
  4789. const enabled = document.getElementById('l2tp-server-enabled').checked;
  4790. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  4791. const profile = document.getElementById('l2tp-server-profile').value;
  4792. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  4793. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  4794. try {
  4795. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  4796. method: 'POST',
  4797. headers: { 'Content-Type': 'application/json' },
  4798. body: JSON.stringify({
  4799. enabled,
  4800. port,
  4801. default_profile: profile,
  4802. use_ipsec: useipsec,
  4803. ipsec_secret: psk
  4804. })
  4805. });
  4806. if (res.ok) {
  4807. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  4808. loadPPPServers();
  4809. fetchData(false);
  4810. } else {
  4811. const err = await res.json();
  4812. showToast('Error', err.message, 'error');
  4813. }
  4814. } catch (err) {
  4815. showToast('Error', err.message, 'error');
  4816. }
  4817. }
  4818. // IPSec Server Modal
  4819. function openIPSecServerModal() {
  4820. loadPPPServers();
  4821. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  4822. }
  4823. function closeIPSecServerModal() {
  4824. document.getElementById('ipsec-server-modal').classList.add('hidden');
  4825. }
  4826. async function submitSaveIPSecServer(e) {
  4827. e.preventDefault();
  4828. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  4829. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  4830. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  4831. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  4832. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  4833. try {
  4834. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  4835. method: 'POST',
  4836. headers: { 'Content-Type': 'application/json' },
  4837. body: JSON.stringify({
  4838. enabled,
  4839. preshared_key: psk,
  4840. pool_address: pool,
  4841. dns_servers: dns,
  4842. local_subnet: subnet
  4843. })
  4844. });
  4845. if (res.ok) {
  4846. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  4847. closeIPSecServerModal();
  4848. loadPPPServers();
  4849. fetchData(false);
  4850. } else {
  4851. const err = await res.json();
  4852. showToast('Error', err.message, 'error');
  4853. }
  4854. } catch (err) {
  4855. showToast('Error', err.message, 'error');
  4856. }
  4857. }
  4858. // WireGuard Client Config Viewer
  4859. let currentWGClientConf = '';
  4860. async function openWGClientConfModal(iface, clientIP) {
  4861. try {
  4862. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  4863. method: 'POST',
  4864. headers: { 'Content-Type': 'application/json' },
  4865. body: JSON.stringify({
  4866. interface: iface,
  4867. address: clientIP || '10.10.0.2/32',
  4868. dns: '1.1.1.1, 8.8.8.8'
  4869. })
  4870. });
  4871. if (res.ok) {
  4872. const data = await res.json();
  4873. currentWGClientConf = data.config;
  4874. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  4875. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  4876. } else {
  4877. const err = await res.json();
  4878. showToast('Error', err.message, 'error');
  4879. }
  4880. } catch (err) {
  4881. showToast('Error', err.message, 'error');
  4882. }
  4883. }
  4884. function closeWGClientConfModal() {
  4885. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  4886. }
  4887. function copyWGClientConf() {
  4888. if (!currentWGClientConf) return;
  4889. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  4890. }
  4891. function downloadWGClientConf() {
  4892. if (!currentWGClientConf) return;
  4893. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  4894. const a = document.createElement('a');
  4895. a.href = URL.createObjectURL(blob);
  4896. a.download = 'wireguard-client.conf';
  4897. document.body.appendChild(a);
  4898. a.click();
  4899. document.body.removeChild(a);
  4900. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  4901. }
  4902. // =========================================================================
  4903. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  4904. // =========================================================================
  4905. state.activeDynSubTab = 'bgp-peers';
  4906. state.activeBgpSubTab = 'bgp-peers';
  4907. state.activeOspfSubTab = 'ospf-ifaces';
  4908. state.bgpInstance = null;
  4909. state.bgpPeers = [];
  4910. state.bgpNets = [];
  4911. state.bgpRoutes = [];
  4912. state.ospfInstance = null;
  4913. state.ospfInterfaces = [];
  4914. state.ospfAreas = [];
  4915. state.ospfNeighbors = [];
  4916. state.ospfRoutes = [];
  4917. function switchBgpSubTab(subTab) {
  4918. state.activeBgpSubTab = subTab;
  4919. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes'];
  4920. tabs.forEach(t => {
  4921. const el = document.getElementById(`dyn-subtab-${t}`);
  4922. const btn = document.getElementById(`bgp-subtab-btn-${t}`);
  4923. if (el) el.classList.toggle('hidden', t !== subTab);
  4924. if (btn) {
  4925. if (t === subTab) {
  4926. 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';
  4927. } else {
  4928. 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';
  4929. }
  4930. }
  4931. });
  4932. }
  4933. function switchOspfSubTab(subTab) {
  4934. state.activeOspfSubTab = subTab;
  4935. const tabs = ['ospf-ifaces', 'ospf-areas', 'ospf-nbrs', 'ospf-routes'];
  4936. tabs.forEach(t => {
  4937. const el = document.getElementById(`dyn-subtab-${t}`);
  4938. const btn = document.getElementById(`ospf-subtab-btn-${t}`);
  4939. if (el) el.classList.toggle('hidden', t !== subTab);
  4940. if (btn) {
  4941. if (t === subTab) {
  4942. 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';
  4943. } else {
  4944. 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';
  4945. }
  4946. }
  4947. });
  4948. }
  4949. function switchDynSubTab(subTab) {
  4950. if (subTab.startsWith('bgp')) {
  4951. if (state.activeTab !== 'bgp') navigate('bgp');
  4952. switchBgpSubTab(subTab);
  4953. } else if (subTab.startsWith('ospf')) {
  4954. if (state.activeTab !== 'ospf') navigate('ospf');
  4955. switchOspfSubTab(subTab);
  4956. }
  4957. }
  4958. async function loadDynamicRouting(showToastMsg = false) {
  4959. try {
  4960. const fetchSafeJson = async (url) => {
  4961. try {
  4962. const r = await fetch(url);
  4963. return r.ok ? await r.json() : null;
  4964. } catch (e) {
  4965. return null;
  4966. }
  4967. };
  4968. const [sum, bgpInst, bgpPeers, bgpNets, bgpRoutes, ospfInst, ospfIfaces, ospfAreas, ospfNbrs, ospfRoutes, filters] = await Promise.all([
  4969. fetchSafeJson(`${API_BASE}/routing/dynamic/summary`),
  4970. fetchSafeJson(`${API_BASE}/routing/bgp/instance`),
  4971. fetchSafeJson(`${API_BASE}/routing/bgp/peers`),
  4972. fetchSafeJson(`${API_BASE}/routing/bgp/networks`),
  4973. fetchSafeJson(`${API_BASE}/routing/bgp/routes`),
  4974. fetchSafeJson(`${API_BASE}/routing/ospf/instance`),
  4975. fetchSafeJson(`${API_BASE}/routing/ospf/interfaces`),
  4976. fetchSafeJson(`${API_BASE}/routing/ospf/areas`),
  4977. fetchSafeJson(`${API_BASE}/routing/ospf/neighbors`),
  4978. fetchSafeJson(`${API_BASE}/routing/ospf/routes`),
  4979. fetchSafeJson(`${API_BASE}/routing/filters`)
  4980. ]);
  4981. if (sum) state.dynSummary = sum;
  4982. if (bgpInst) state.bgpInstance = bgpInst;
  4983. if (bgpPeers) state.bgpPeers = bgpPeers;
  4984. if (bgpNets) state.bgpNets = bgpNets;
  4985. if (bgpRoutes) state.bgpRoutes = bgpRoutes;
  4986. if (ospfInst) state.ospfInstance = ospfInst;
  4987. if (ospfIfaces) state.ospfInterfaces = ospfIfaces;
  4988. if (ospfAreas) state.ospfAreas = ospfAreas;
  4989. if (ospfNbrs) state.ospfNeighbors = ospfNbrs;
  4990. if (ospfRoutes) state.ospfRoutes = ospfRoutes;
  4991. if (filters) state.routingFilters = filters;
  4992. try { renderBgpStatusPill(); } catch(e) { console.error('renderBgpStatusPill error:', e); }
  4993. try { renderBgpPeers(); } catch(e) { console.error('renderBgpPeers error:', e); }
  4994. try { renderBgpNetworks(); } catch(e) { console.error('renderBgpNetworks error:', e); }
  4995. try { renderBgpRoutes(); } catch(e) { console.error('renderBgpRoutes error:', e); }
  4996. try { renderOspfStatusPill(); } catch(e) { console.error('renderOspfStatusPill error:', e); }
  4997. try { renderOspfInterfaces(); } catch(e) { console.error('renderOspfInterfaces error:', e); }
  4998. try { renderOspfAreas(); } catch(e) { console.error('renderOspfAreas error:', e); }
  4999. try { renderOspfNeighbors(); } catch(e) { console.error('renderOspfNeighbors error:', e); }
  5000. try { renderOspfRoutes(); } catch(e) { console.error('renderOspfRoutes error:', e); }
  5001. try { renderRoutingFilters(); } catch(e) { console.error('renderRoutingFilters error:', e); }
  5002. try { updateBadges(); } catch(e) { console.error('updateBadges error:', e); }
  5003. if (showToastMsg) showToast('Refreshed', 'Dynamic routing telemetry updated', 'info');
  5004. } catch (err) {
  5005. console.error('Failed to load dynamic routing:', err);
  5006. if (showToastMsg) showToast('Notice', 'Unable to refresh dynamic routing telemetry', 'warning');
  5007. }
  5008. }
  5009. function renderBgpStatusPill() {
  5010. const pill = document.getElementById('bgp-live-status-pill');
  5011. if (!pill) return;
  5012. const inst = state.bgpInstance;
  5013. if (!inst || !inst.enabled) {
  5014. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  5015. pill.innerText = 'BGP DISABLED';
  5016. } else if (inst.running) {
  5017. 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';
  5018. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  5019. } else {
  5020. 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';
  5021. pill.innerText = 'BGP STARTING...';
  5022. }
  5023. }
  5024. function renderBgpPeers() {
  5025. const tbody = document.getElementById('bgp-peers-table-body');
  5026. if (!tbody) return;
  5027. const empty = document.getElementById('bgp-peers-empty');
  5028. const countBadge = document.getElementById('bgp-peers-count-badge');
  5029. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  5030. const peers = state.bgpPeers || [];
  5031. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  5032. if (navBadge) navBadge.innerText = peers.length;
  5033. if (peers.length === 0) {
  5034. tbody.innerHTML = '';
  5035. if (empty) empty.classList.remove('hidden');
  5036. return;
  5037. }
  5038. if (empty) empty.classList.add('hidden');
  5039. tbody.innerHTML = peers.map(p => {
  5040. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  5041. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  5042. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  5043. let stateBadge = '';
  5044. if (p.disabled) {
  5045. 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>';
  5046. } else if (p.state === 'Established') {
  5047. 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>';
  5048. } else if (p.state === 'Connect' || p.state === 'Active') {
  5049. 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>`;
  5050. } else {
  5051. 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>`;
  5052. }
  5053. return `
  5054. <tr class="hover:bg-slate-800/40 transition">
  5055. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  5056. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  5057. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  5058. <td class="py-2.5 px-3 font-bold text-slate-200">AS ${p.remote_as}</td>
  5059. <td class="py-2.5 px-3">${stateBadge}</td>
  5060. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  5061. <td class="py-2.5 px-3 text-slate-300">
  5062. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  5063. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  5064. </td>
  5065. <td class="py-2.5 px-3 font-mono text-[11px] whitespace-nowrap">
  5066. ${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> ` : ''}
  5067. ${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>` : ''}
  5068. ${!p.in_filter && !p.out_filter ? '<span class="text-slate-600">-</span>' : ''}
  5069. </td>
  5070. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  5071. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  5072. <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'}">
  5073. ${p.disabled ? 'Enable' : 'Disable'}
  5074. </button>
  5075. <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">
  5076. Edit
  5077. </button>
  5078. <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">
  5079. Delete
  5080. </button>
  5081. </td>
  5082. </tr>
  5083. `;
  5084. }).join('');
  5085. }
  5086. function renderBgpNetworks() {
  5087. const tbody = document.getElementById('bgp-nets-table-body');
  5088. if (!tbody) return;
  5089. const empty = document.getElementById('bgp-nets-empty');
  5090. const countBadge = document.getElementById('bgp-nets-count-badge');
  5091. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  5092. const nets = state.bgpNets || [];
  5093. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  5094. if (navBadge) navBadge.innerText = nets.length;
  5095. if (nets.length === 0) {
  5096. tbody.innerHTML = '';
  5097. if (empty) empty.classList.remove('hidden');
  5098. return;
  5099. }
  5100. if (empty) empty.classList.add('hidden');
  5101. tbody.innerHTML = nets.map(n => `
  5102. <tr class="hover:bg-slate-800/40 transition">
  5103. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  5104. <td class="py-2.5 px-3">
  5105. ${n.disabled
  5106. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  5107. : '<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>'}
  5108. </td>
  5109. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  5110. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  5111. <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">
  5112. Delete
  5113. </button>
  5114. </td>
  5115. </tr>
  5116. `).join('');
  5117. }
  5118. function renderBgpRoutes() {
  5119. const tbody = document.getElementById('bgp-routes-table-body');
  5120. if (!tbody) return;
  5121. const empty = document.getElementById('bgp-routes-empty');
  5122. const countBadge = document.getElementById('bgp-routes-count-badge');
  5123. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  5124. const routes = state.bgpRoutes || [];
  5125. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  5126. if (navBadge) navBadge.innerText = routes.length;
  5127. if (routes.length === 0) {
  5128. tbody.innerHTML = '';
  5129. if (empty) empty.classList.remove('hidden');
  5130. return;
  5131. }
  5132. if (empty) empty.classList.add('hidden');
  5133. tbody.innerHTML = routes.map(r => `
  5134. <tr class="hover:bg-slate-800/40 transition">
  5135. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  5136. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  5137. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  5138. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  5139. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  5140. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  5141. </tr>
  5142. `).join('');
  5143. }
  5144. function renderOspfStatusPill() {
  5145. const pill = document.getElementById('ospf-live-status-pill');
  5146. if (!pill) return;
  5147. const inst = state.ospfInstance;
  5148. if (!inst || !inst.enabled) {
  5149. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  5150. pill.innerText = 'OSPF DISABLED';
  5151. } else if (inst.running) {
  5152. 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';
  5153. pill.innerText = `OSPF ACTIVE (ID: ${inst.router_id || 'Auto'})`;
  5154. } else {
  5155. 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';
  5156. pill.innerText = 'OSPF STARTING...';
  5157. }
  5158. }
  5159. function renderOspfInterfaces() {
  5160. const tbody = document.getElementById('ospf-ifaces-table-body');
  5161. if (!tbody) return;
  5162. const empty = document.getElementById('ospf-ifaces-empty');
  5163. const countBadge = document.getElementById('ospf-ifaces-count-badge');
  5164. const navBadge = document.getElementById('dyn-badge-ospf-ifaces');
  5165. const ifaces = state.ospfInterfaces || [];
  5166. if (countBadge) countBadge.innerText = `${ifaces.length} Interfaces`;
  5167. if (navBadge) navBadge.innerText = ifaces.length;
  5168. if (ifaces.length === 0) {
  5169. tbody.innerHTML = '';
  5170. if (empty) empty.classList.remove('hidden');
  5171. return;
  5172. }
  5173. if (empty) empty.classList.add('hidden');
  5174. tbody.innerHTML = ifaces.map(i => {
  5175. let flagA = !i.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  5176. let flagP = i.passive ? '<span class="text-amber-400 font-bold ml-1" title="Passive">P</span>' : '';
  5177. let flagX = i.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  5178. return `
  5179. <tr class="hover:bg-slate-800/40 transition">
  5180. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagP}${flagX}</td>
  5181. <td class="py-2.5 px-3 font-semibold text-white font-mono">${escapeHtml(i.network)}</td>
  5182. <td class="py-2.5 px-3 text-indigo-300 font-bold">Area ${escapeHtml(i.area)}</td>
  5183. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(i.interface || 'Any')}</td>
  5184. <td class="py-2.5 px-3 text-slate-300">${i.cost}</td>
  5185. <td class="py-2.5 px-3 text-slate-300">${i.priority}</td>
  5186. <td class="py-2.5 px-3 text-slate-400">${i.hello_interval}s / ${i.dead_interval}s</td>
  5187. <td class="py-2.5 px-3 text-slate-300 uppercase">${escapeHtml(i.auth_type || 'none')}</td>
  5188. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(i.comment || '')}</td>
  5189. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  5190. <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'}">
  5191. ${i.disabled ? 'Enable' : 'Disable'}
  5192. </button>
  5193. <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">
  5194. Edit
  5195. </button>
  5196. <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">
  5197. Delete
  5198. </button>
  5199. </td>
  5200. </tr>
  5201. `;
  5202. }).join('');
  5203. }
  5204. function renderOspfAreas() {
  5205. const tbody = document.getElementById('ospf-areas-table-body');
  5206. if (!tbody) return;
  5207. const countBadge = document.getElementById('ospf-areas-count-badge');
  5208. const navBadge = document.getElementById('dyn-badge-ospf-areas');
  5209. const areas = state.ospfAreas || [];
  5210. if (countBadge) countBadge.innerText = `${areas.length} Areas`;
  5211. if (navBadge) navBadge.innerText = areas.length;
  5212. tbody.innerHTML = areas.map(a => `
  5213. <tr class="hover:bg-slate-800/40 transition">
  5214. <td class="py-2.5 px-3 font-semibold text-white font-mono">${escapeHtml(a.name)}</td>
  5215. <td class="py-2.5 px-3 font-bold text-indigo-300">${escapeHtml(a.area_id)}</td>
  5216. <td class="py-2.5 px-3 text-slate-300 uppercase">${escapeHtml(a.area_type || 'default')}</td>
  5217. <td class="py-2.5 px-3 text-slate-400 font-sans">${escapeHtml(a.comment || '')}</td>
  5218. <td class="py-2.5 px-3 text-right font-sans">
  5219. <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">
  5220. Delete
  5221. </button>
  5222. </td>
  5223. </tr>
  5224. `).join('');
  5225. }
  5226. function renderOspfNeighbors() {
  5227. const tbody = document.getElementById('ospf-nbrs-table-body');
  5228. if (!tbody) return;
  5229. const empty = document.getElementById('ospf-nbrs-empty');
  5230. const countBadge = document.getElementById('ospf-nbrs-count-badge');
  5231. const navBadge = document.getElementById('dyn-badge-ospf-nbrs');
  5232. const nbrs = state.ospfNeighbors || [];
  5233. if (countBadge) countBadge.innerText = `${nbrs.length} Neighbors`;
  5234. if (navBadge) navBadge.innerText = nbrs.length;
  5235. if (nbrs.length === 0) {
  5236. tbody.innerHTML = '';
  5237. if (empty) empty.classList.remove('hidden');
  5238. return;
  5239. }
  5240. if (empty) empty.classList.add('hidden');
  5241. tbody.innerHTML = nbrs.map(n => {
  5242. let stateBadge = '';
  5243. if (n.state && (n.state.startsWith('Full') || n.state.includes('DR') || n.state.includes('Backup'))) {
  5244. 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>`;
  5245. } else {
  5246. 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>`;
  5247. }
  5248. return `
  5249. <tr class="hover:bg-slate-800/40 transition">
  5250. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(n.neighbor_id)}</td>
  5251. <td class="py-2.5 px-3 text-indigo-300 font-bold">${escapeHtml(n.address)}</td>
  5252. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(n.interface)}</td>
  5253. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(n.area || '0.0.0.0')}</td>
  5254. <td class="py-2.5 px-3">${stateBadge}</td>
  5255. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(n.dead_timer || '-')}</td>
  5256. </tr>
  5257. `;
  5258. }).join('');
  5259. }
  5260. function renderOspfRoutes() {
  5261. const tbody = document.getElementById('ospf-routes-table-body');
  5262. if (!tbody) return;
  5263. const empty = document.getElementById('ospf-routes-empty');
  5264. const countBadge = document.getElementById('ospf-routes-count-badge');
  5265. const navBadge = document.getElementById('dyn-badge-ospf-routes');
  5266. const routes = state.ospfRoutes || [];
  5267. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  5268. if (navBadge) navBadge.innerText = routes.length;
  5269. if (routes.length === 0) {
  5270. tbody.innerHTML = '';
  5271. if (empty) empty.classList.remove('hidden');
  5272. return;
  5273. }
  5274. if (empty) empty.classList.add('hidden');
  5275. tbody.innerHTML = routes.map(r => `
  5276. <tr class="hover:bg-slate-800/40 transition">
  5277. <td class="py-2.5 px-3 font-semibold text-white font-mono">${escapeHtml(r.prefix)}</td>
  5278. <td class="py-2.5 px-3 text-slate-300">${escapeHtml(r.route_type || 'Network')}</td>
  5279. <td class="py-2.5 px-3 text-slate-300">${r.cost}</td>
  5280. <td class="py-2.5 px-3 text-indigo-300 font-bold">Area ${escapeHtml(r.area || '0.0.0.0')}</td>
  5281. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(r.next_hop || r.interface || '-')}</td>
  5282. </tr>
  5283. `).join('');
  5284. }
  5285. // BGP Modals & Actions
  5286. function openBgpInstanceModal() {
  5287. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  5288. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  5289. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  5290. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  5291. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  5292. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  5293. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  5294. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  5295. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  5296. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  5297. }
  5298. function closeBgpInstanceModal() {
  5299. document.getElementById('bgp-instance-modal').classList.add('hidden');
  5300. }
  5301. async function submitBgpInstance(e) {
  5302. e.preventDefault();
  5303. const payload = {
  5304. enabled: document.getElementById('modal-bgp-enabled').checked,
  5305. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  5306. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  5307. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  5308. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  5309. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  5310. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  5311. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  5312. };
  5313. try {
  5314. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  5315. method: 'POST',
  5316. headers: { 'Content-Type': 'application/json' },
  5317. body: JSON.stringify(payload)
  5318. });
  5319. if (res.ok) {
  5320. closeBgpInstanceModal();
  5321. showToast('Success', 'BGP instance configuration updated', 'success');
  5322. loadDynamicRouting();
  5323. } else {
  5324. const err = await res.json();
  5325. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  5326. }
  5327. } catch (err) {
  5328. showToast('Error', err.message, 'error');
  5329. }
  5330. }
  5331. function openAddBgpPeerModal() {
  5332. document.getElementById('bgp-peer-form').reset();
  5333. document.getElementById('modal-bgp-peer-id').value = '';
  5334. document.getElementById('bgp-peer-modal-title').innerText = 'Add BGP Peer Connection';
  5335. document.getElementById('modal-bgp-peer-nexthop-self').checked = true;
  5336. const inFilterEl = document.getElementById('modal-bgp-peer-in-filter');
  5337. if (inFilterEl) inFilterEl.value = '';
  5338. const outFilterEl = document.getElementById('modal-bgp-peer-out-filter');
  5339. if (outFilterEl) outFilterEl.value = '';
  5340. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  5341. }
  5342. function openEditBgpPeerModal(id) {
  5343. const p = (state.bgpPeers || []).find(item => item.id === id);
  5344. if (!p) return;
  5345. document.getElementById('modal-bgp-peer-id').value = p.id;
  5346. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  5347. document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  5348. document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  5349. document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  5350. document.getElementById('modal-bgp-peer-password').value = p.password || '';
  5351. document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  5352. document.getElementById('modal-bgp-peer-nexthop-self').checked = !!p.nexthop_self;
  5353. document.getElementById('modal-bgp-peer-passive').checked = !!p.passive;
  5354. document.getElementById('modal-bgp-peer-disabled').checked = !!p.disabled;
  5355. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  5356. const inFilterEl = document.getElementById('modal-bgp-peer-in-filter');
  5357. if (inFilterEl) inFilterEl.value = p.in_filter || '';
  5358. const outFilterEl = document.getElementById('modal-bgp-peer-out-filter');
  5359. if (outFilterEl) outFilterEl.value = p.out_filter || '';
  5360. document.getElementById('bgp-peer-modal-title').innerText = 'Edit BGP Peer Connection';
  5361. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  5362. }
  5363. function closeBgpPeerModal() {
  5364. document.getElementById('bgp-peer-modal').classList.add('hidden');
  5365. }
  5366. async function submitBgpPeer(e) {
  5367. e.preventDefault();
  5368. const payload = {
  5369. id: document.getElementById('modal-bgp-peer-id').value,
  5370. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  5371. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  5372. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10),
  5373. local_address: document.getElementById('modal-bgp-peer-local-addr').value.trim(),
  5374. password: document.getElementById('modal-bgp-peer-password').value,
  5375. multihop: document.getElementById('modal-bgp-peer-multihop').checked,
  5376. nexthop_self: document.getElementById('modal-bgp-peer-nexthop-self').checked,
  5377. passive: document.getElementById('modal-bgp-peer-passive').checked,
  5378. disabled: document.getElementById('modal-bgp-peer-disabled').checked,
  5379. in_filter: (document.getElementById('modal-bgp-peer-in-filter')?.value || '').trim(),
  5380. out_filter: (document.getElementById('modal-bgp-peer-out-filter')?.value || '').trim(),
  5381. comment: document.getElementById('modal-bgp-peer-comment').value.trim()
  5382. };
  5383. try {
  5384. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  5385. method: 'POST',
  5386. headers: { 'Content-Type': 'application/json' },
  5387. body: JSON.stringify(payload)
  5388. });
  5389. if (res.ok) {
  5390. closeBgpPeerModal();
  5391. showToast('Success', 'BGP Peer saved', 'success');
  5392. loadDynamicRouting();
  5393. } else {
  5394. const err = await res.json();
  5395. showToast('Error', err.error || 'Failed to save peer', 'error');
  5396. }
  5397. } catch (err) {
  5398. showToast('Error', err.message, 'error');
  5399. }
  5400. }
  5401. async function deleteBgpPeer(id) {
  5402. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  5403. try {
  5404. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5405. if (res.ok) {
  5406. showToast('Deleted', 'BGP peer removed', 'success');
  5407. loadDynamicRouting();
  5408. }
  5409. } catch (err) {
  5410. showToast('Error', err.message, 'error');
  5411. }
  5412. }
  5413. async function toggleBgpPeerState(id, disabled) {
  5414. try {
  5415. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  5416. method: 'POST',
  5417. headers: { 'Content-Type': 'application/json' },
  5418. body: JSON.stringify({ disabled })
  5419. });
  5420. if (res.ok) {
  5421. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  5422. loadDynamicRouting();
  5423. }
  5424. } catch (err) {
  5425. showToast('Error', err.message, 'error');
  5426. }
  5427. }
  5428. function openAddBgpNetworkModal() {
  5429. document.getElementById('bgp-network-form').reset();
  5430. document.getElementById('modal-bgp-net-id').value = '';
  5431. document.getElementById('bgp-network-modal').classList.remove('hidden');
  5432. }
  5433. function closeBgpNetworkModal() {
  5434. document.getElementById('bgp-network-modal').classList.add('hidden');
  5435. }
  5436. async function submitBgpNetwork(e) {
  5437. e.preventDefault();
  5438. const payload = {
  5439. id: document.getElementById('modal-bgp-net-id').value,
  5440. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  5441. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  5442. disabled: document.getElementById('modal-bgp-net-disabled').checked
  5443. };
  5444. try {
  5445. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  5446. method: 'POST',
  5447. headers: { 'Content-Type': 'application/json' },
  5448. body: JSON.stringify(payload)
  5449. });
  5450. if (res.ok) {
  5451. closeBgpNetworkModal();
  5452. showToast('Success', 'BGP network advertisement saved', 'success');
  5453. loadDynamicRouting();
  5454. } else {
  5455. const err = await res.json();
  5456. showToast('Error', err.error || 'Failed to save network', 'error');
  5457. }
  5458. } catch (err) {
  5459. showToast('Error', err.message, 'error');
  5460. }
  5461. }
  5462. async function deleteBgpNetwork(id) {
  5463. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  5464. try {
  5465. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5466. if (res.ok) {
  5467. showToast('Deleted', 'Network advertisement removed', 'success');
  5468. loadDynamicRouting();
  5469. }
  5470. } catch (err) {
  5471. showToast('Error', err.message, 'error');
  5472. }
  5473. }
  5474. // OSPF Modals & Actions
  5475. function openOspfInstanceModal() {
  5476. const inst = state.ospfInstance || { enabled: false, router_id: '192.168.131.56', default_metric: 10 };
  5477. document.getElementById('modal-ospf-enabled').checked = !!inst.enabled;
  5478. document.getElementById('modal-ospf-router-id').value = inst.router_id || '';
  5479. document.getElementById('modal-ospf-metric').value = inst.default_metric || 10;
  5480. document.getElementById('modal-ospf-redist-conn').checked = !!inst.redistribute_connected;
  5481. document.getElementById('modal-ospf-redist-static').checked = !!inst.redistribute_static;
  5482. document.getElementById('modal-ospf-redist-bgp').checked = !!inst.redistribute_bgp;
  5483. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  5484. }
  5485. function closeOspfInstanceModal() {
  5486. document.getElementById('ospf-instance-modal').classList.add('hidden');
  5487. }
  5488. async function submitOspfInstance(e) {
  5489. e.preventDefault();
  5490. const payload = {
  5491. enabled: document.getElementById('modal-ospf-enabled').checked,
  5492. router_id: document.getElementById('modal-ospf-router-id').value.trim(),
  5493. default_metric: parseInt(document.getElementById('modal-ospf-metric').value, 10),
  5494. redistribute_connected: document.getElementById('modal-ospf-redist-conn').checked,
  5495. redistribute_static: document.getElementById('modal-ospf-redist-static').checked,
  5496. redistribute_bgp: document.getElementById('modal-ospf-redist-bgp').checked
  5497. };
  5498. try {
  5499. const res = await fetch(`${API_BASE}/routing/ospf/instance`, {
  5500. method: 'POST',
  5501. headers: { 'Content-Type': 'application/json' },
  5502. body: JSON.stringify(payload)
  5503. });
  5504. if (res.ok) {
  5505. closeOspfInstanceModal();
  5506. showToast('Success', 'OSPF instance configuration updated', 'success');
  5507. loadDynamicRouting();
  5508. } else {
  5509. const err = await res.json();
  5510. showToast('Error', err.error || 'Failed to update OSPF instance', 'error');
  5511. }
  5512. } catch (err) {
  5513. showToast('Error', err.message, 'error');
  5514. }
  5515. }
  5516. function openAddOspfAreaModal() {
  5517. document.getElementById('ospf-area-form').reset();
  5518. document.getElementById('modal-ospf-area-id').value = '';
  5519. document.getElementById('modal-ospf-area-areaid').value = '0.0.0.0';
  5520. document.getElementById('ospf-area-modal').classList.remove('hidden');
  5521. }
  5522. function closeOspfAreaModal() {
  5523. document.getElementById('ospf-area-modal').classList.add('hidden');
  5524. }
  5525. async function submitOspfArea(e) {
  5526. e.preventDefault();
  5527. const payload = {
  5528. id: document.getElementById('modal-ospf-area-id').value,
  5529. name: document.getElementById('modal-ospf-area-name').value.trim(),
  5530. area_id: document.getElementById('modal-ospf-area-areaid').value.trim(),
  5531. area_type: document.getElementById('modal-ospf-area-type').value,
  5532. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  5533. };
  5534. try {
  5535. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  5536. method: 'POST',
  5537. headers: { 'Content-Type': 'application/json' },
  5538. body: JSON.stringify(payload)
  5539. });
  5540. if (res.ok) {
  5541. closeOspfAreaModal();
  5542. showToast('Success', 'OSPF area saved', 'success');
  5543. loadDynamicRouting();
  5544. } else {
  5545. const err = await res.json();
  5546. showToast('Error', err.error || 'Failed to save area', 'error');
  5547. }
  5548. } catch (err) {
  5549. showToast('Error', err.message, 'error');
  5550. }
  5551. }
  5552. async function deleteOspfArea(id) {
  5553. if (!confirm('Are you sure you want to delete this OSPF area?')) return;
  5554. try {
  5555. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5556. if (res.ok) {
  5557. showToast('Deleted', 'OSPF area removed', 'success');
  5558. loadDynamicRouting();
  5559. }
  5560. } catch (err) {
  5561. showToast('Error', err.message, 'error');
  5562. }
  5563. }
  5564. function populateOspfInterfaceDevices() {
  5565. const select = document.getElementById('modal-ospf-iface-device');
  5566. if (!select) return;
  5567. const current = select.value;
  5568. select.innerHTML = '<option value="">Any matching interface</option>';
  5569. (state.interfaces || []).forEach(iface => {
  5570. select.innerHTML += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)} (${iface.type})</option>`;
  5571. });
  5572. if (current) select.value = current;
  5573. }
  5574. function openAddOspfInterfaceModal() {
  5575. document.getElementById('ospf-interface-form').reset();
  5576. document.getElementById('modal-ospf-iface-id').value = '';
  5577. document.getElementById('modal-ospf-iface-area').value = '0.0.0.0';
  5578. document.getElementById('modal-ospf-iface-cost').value = '10';
  5579. document.getElementById('modal-ospf-iface-priority').value = '1';
  5580. document.getElementById('modal-ospf-iface-hello').value = '10';
  5581. document.getElementById('modal-ospf-iface-dead').value = '40';
  5582. document.getElementById('ospf-interface-modal-title').innerText = 'Add OSPF Interface';
  5583. populateOspfInterfaceDevices();
  5584. document.getElementById('ospf-interface-modal').classList.remove('hidden');
  5585. }
  5586. function openEditOspfInterfaceModal(id) {
  5587. const item = (state.ospfInterfaces || []).find(i => i.id === id);
  5588. if (!item) return;
  5589. populateOspfInterfaceDevices();
  5590. document.getElementById('modal-ospf-iface-id').value = item.id;
  5591. document.getElementById('modal-ospf-iface-net').value = item.network || '';
  5592. document.getElementById('modal-ospf-iface-area').value = item.area || '0.0.0.0';
  5593. document.getElementById('modal-ospf-iface-device').value = item.interface || '';
  5594. document.getElementById('modal-ospf-iface-cost').value = item.cost || 10;
  5595. document.getElementById('modal-ospf-iface-priority').value = item.priority || 1;
  5596. document.getElementById('modal-ospf-iface-hello').value = item.hello_interval || 10;
  5597. document.getElementById('modal-ospf-iface-dead').value = item.dead_interval || 40;
  5598. document.getElementById('modal-ospf-iface-auth-type').value = item.auth_type || 'none';
  5599. document.getElementById('modal-ospf-iface-auth-key').value = item.auth_key || '';
  5600. document.getElementById('modal-ospf-iface-passive').checked = !!item.passive;
  5601. document.getElementById('modal-ospf-iface-disabled').checked = !!item.disabled;
  5602. document.getElementById('modal-ospf-iface-comment').value = item.comment || '';
  5603. document.getElementById('ospf-interface-modal-title').innerText = 'Edit OSPF Interface';
  5604. document.getElementById('ospf-interface-modal').classList.remove('hidden');
  5605. }
  5606. function closeOspfInterfaceModal() {
  5607. document.getElementById('ospf-interface-modal').classList.add('hidden');
  5608. }
  5609. async function submitOspfInterface(e) {
  5610. e.preventDefault();
  5611. const payload = {
  5612. id: document.getElementById('modal-ospf-iface-id').value,
  5613. network: document.getElementById('modal-ospf-iface-net').value.trim(),
  5614. area: document.getElementById('modal-ospf-iface-area').value.trim(),
  5615. interface: document.getElementById('modal-ospf-iface-device').value,
  5616. cost: parseInt(document.getElementById('modal-ospf-iface-cost').value, 10),
  5617. priority: parseInt(document.getElementById('modal-ospf-iface-priority').value, 10),
  5618. hello_interval: parseInt(document.getElementById('modal-ospf-iface-hello').value, 10),
  5619. dead_interval: parseInt(document.getElementById('modal-ospf-iface-dead').value, 10),
  5620. auth_type: document.getElementById('modal-ospf-iface-auth-type').value,
  5621. auth_key: document.getElementById('modal-ospf-iface-auth-key').value,
  5622. passive: document.getElementById('modal-ospf-iface-passive').checked,
  5623. disabled: document.getElementById('modal-ospf-iface-disabled').checked,
  5624. comment: document.getElementById('modal-ospf-iface-comment').value.trim()
  5625. };
  5626. try {
  5627. const res = await fetch(`${API_BASE}/routing/ospf/interfaces`, {
  5628. method: 'POST',
  5629. headers: { 'Content-Type': 'application/json' },
  5630. body: JSON.stringify(payload)
  5631. });
  5632. if (res.ok) {
  5633. closeOspfInterfaceModal();
  5634. showToast('Success', 'OSPF interface template saved', 'success');
  5635. loadDynamicRouting();
  5636. } else {
  5637. const err = await res.json();
  5638. showToast('Error', err.error || 'Failed to save interface', 'error');
  5639. }
  5640. } catch (err) {
  5641. showToast('Error', err.message, 'error');
  5642. }
  5643. }
  5644. async function deleteOspfInterface(id) {
  5645. if (!confirm('Are you sure you want to delete this OSPF interface?')) return;
  5646. try {
  5647. const res = await fetch(`${API_BASE}/routing/ospf/interfaces/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5648. if (res.ok) {
  5649. showToast('Deleted', 'OSPF interface removed', 'success');
  5650. loadDynamicRouting();
  5651. }
  5652. } catch (err) {
  5653. showToast('Error', err.message, 'error');
  5654. }
  5655. }
  5656. async function toggleOspfInterfaceState(id, disabled) {
  5657. try {
  5658. const res = await fetch(`${API_BASE}/routing/ospf/interfaces/${encodeURIComponent(id)}/state`, {
  5659. method: 'POST',
  5660. headers: { 'Content-Type': 'application/json' },
  5661. body: JSON.stringify({ disabled })
  5662. });
  5663. if (res.ok) {
  5664. showToast('Updated', `Interface ${disabled ? 'disabled' : 'enabled'}`, 'success');
  5665. loadDynamicRouting();
  5666. }
  5667. } catch (err) {
  5668. showToast('Error', err.message, 'error');
  5669. }
  5670. }
  5671. // ============================================================================
  5672. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  5673. // ============================================================================
  5674. function switchBridgeSubTab(tab) {
  5675. state.bridgeSubTab = tab;
  5676. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  5677. tabs.forEach(t => {
  5678. const panel = document.getElementById(`bridge-subtab-${t}`);
  5679. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  5680. if (panel) {
  5681. if (t === tab) panel.classList.remove('hidden');
  5682. else panel.classList.add('hidden');
  5683. }
  5684. if (btn) {
  5685. if (t === tab) {
  5686. 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';
  5687. } else {
  5688. 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';
  5689. }
  5690. }
  5691. });
  5692. const addBtn = document.getElementById('bridge-top-action-btn');
  5693. if (addBtn) {
  5694. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  5695. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  5696. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  5697. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  5698. }
  5699. if (tab === 'hosts') loadBridgeHosts();
  5700. }
  5701. function openCurrentBridgeModal() {
  5702. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  5703. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  5704. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  5705. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  5706. }
  5707. async function loadBridge() {
  5708. try {
  5709. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vlanIfacesRes] = await Promise.all([
  5710. fetch(`${API_BASE}/bridge/bridges`),
  5711. fetch(`${API_BASE}/bridge/ports`),
  5712. fetch(`${API_BASE}/bridge/vlans`),
  5713. fetch(`${API_BASE}/bridge/summary`),
  5714. fetch(`${API_BASE}/vpn/eoip`),
  5715. fetch(`${API_BASE}/vlans`)
  5716. ]);
  5717. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  5718. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  5719. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  5720. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  5721. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  5722. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  5723. // Badges & Stats
  5724. const bBridges = document.getElementById('bridge-badge-bridges');
  5725. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  5726. const bPorts = document.getElementById('bridge-badge-ports');
  5727. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  5728. const bVlans = document.getElementById('bridge-badge-vlans');
  5729. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  5730. const bHosts = document.getElementById('bridge-badge-hosts');
  5731. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  5732. const sBr = document.getElementById('bridge-stat-bridges');
  5733. if (sBr) sBr.innerText = (state.bridges || []).length;
  5734. const sPorts = document.getElementById('bridge-stat-ports');
  5735. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  5736. const sHosts = document.getElementById('bridge-stat-hosts');
  5737. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  5738. renderBridges();
  5739. renderBridgePorts();
  5740. renderBridgeVLANs();
  5741. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  5742. } catch (err) {
  5743. console.error('Failed to load bridge subsystem:', err);
  5744. }
  5745. }
  5746. // ----------------- Bridges -----------------
  5747. function renderBridges() {
  5748. const tbody = document.getElementById('bridge-table-body');
  5749. const empty = document.getElementById('bridge-empty-bridges');
  5750. const countBadge = document.getElementById('bridge-count-badge');
  5751. if (!tbody) return;
  5752. tbody.innerHTML = '';
  5753. const bridges = state.bridges || [];
  5754. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  5755. if (bridges.length === 0) {
  5756. empty?.classList.remove('hidden');
  5757. return;
  5758. }
  5759. empty?.classList.add('hidden');
  5760. bridges.forEach((b, idx) => {
  5761. const tr = document.createElement('tr');
  5762. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  5763. // Format IP addresses pill list
  5764. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  5765. if (b.ip_addresses && b.ip_addresses.length > 0) {
  5766. ipsHtml = b.ip_addresses.map(ip => `
  5767. <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">
  5768. <span>${ip}</span>
  5769. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  5770. </span>
  5771. `).join(' ');
  5772. }
  5773. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  5774. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  5775. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  5776. tr.innerHTML = `
  5777. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  5778. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  5779. <td class="py-2.5 px-3 font-bold text-white text-sm">
  5780. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  5781. </td>
  5782. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  5783. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  5784. <td class="py-2.5 px-3">
  5785. <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>
  5786. </td>
  5787. <td class="py-2.5 px-3 text-center">
  5788. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  5789. </td>
  5790. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  5791. <td class="py-2.5 px-3">
  5792. <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>
  5793. </td>
  5794. <td class="py-2.5 px-3">
  5795. <div class="flex items-center gap-1.5 flex-wrap">
  5796. ${ipsHtml}
  5797. <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>
  5798. </div>
  5799. </td>
  5800. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  5801. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  5802. </td>
  5803. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  5804. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  5805. <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>
  5806. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  5807. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5808. </td>
  5809. `;
  5810. tbody.appendChild(tr);
  5811. });
  5812. }
  5813. function openAddBridgeModal() {
  5814. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  5815. document.getElementById('bridge-modal-id').value = '';
  5816. document.getElementById('bridge-modal-name').value = 'bridge1';
  5817. document.getElementById('bridge-modal-name').disabled = false;
  5818. document.getElementById('bridge-modal-mtu').value = '1500';
  5819. document.getElementById('bridge-modal-mac').value = '';
  5820. document.getElementById('bridge-modal-stp').value = 'rstp';
  5821. document.getElementById('bridge-modal-priority').value = '32768';
  5822. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  5823. document.getElementById('bridge-modal-pvid').value = '1';
  5824. document.getElementById('bridge-modal-fastforward').checked = true;
  5825. document.getElementById('bridge-modal-comment').value = '';
  5826. document.getElementById('bridge-modal-disabled').checked = false;
  5827. toggleBridgeModalVlanFiltering();
  5828. document.getElementById('bridge-modal').classList.remove('hidden');
  5829. }
  5830. function openEditBridgeModal(id) {
  5831. const b = (state.bridges || []).find(x => x.id === id);
  5832. if (!b) return;
  5833. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  5834. document.getElementById('bridge-modal-id').value = b.id;
  5835. document.getElementById('bridge-modal-name').value = b.name;
  5836. document.getElementById('bridge-modal-name').disabled = true;
  5837. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  5838. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  5839. document.getElementById('bridge-modal-stp').value = b.stp || 'rstp';
  5840. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  5841. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  5842. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  5843. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  5844. document.getElementById('bridge-modal-comment').value = b.comment || '';
  5845. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  5846. toggleBridgeModalVlanFiltering();
  5847. document.getElementById('bridge-modal').classList.remove('hidden');
  5848. }
  5849. function closeBridgeModal() {
  5850. document.getElementById('bridge-modal').classList.add('hidden');
  5851. }
  5852. function toggleBridgeModalVlanFiltering() {
  5853. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  5854. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  5855. if (pvidBox) {
  5856. if (chk) pvidBox.classList.remove('opacity-40');
  5857. else pvidBox.classList.add('opacity-40');
  5858. }
  5859. }
  5860. async function submitSaveBridge(e) {
  5861. e.preventDefault();
  5862. const id = document.getElementById('bridge-modal-id').value;
  5863. const name = document.getElementById('bridge-modal-name').value.trim();
  5864. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  5865. const mac = document.getElementById('bridge-modal-mac').value.trim();
  5866. const stp = document.getElementById('bridge-modal-stp').value;
  5867. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  5868. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  5869. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  5870. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  5871. const comment = document.getElementById('bridge-modal-comment').value.trim();
  5872. const disabled = document.getElementById('bridge-modal-disabled').checked;
  5873. try {
  5874. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  5875. method: 'POST',
  5876. headers: { 'Content-Type': 'application/json' },
  5877. body: JSON.stringify({
  5878. id,
  5879. name,
  5880. mtu,
  5881. mac_address: mac,
  5882. stp,
  5883. priority,
  5884. vlan_filtering: vlanFiltering,
  5885. pvid,
  5886. fast_forward: fastForward,
  5887. comment,
  5888. disabled
  5889. })
  5890. });
  5891. if (res.ok) {
  5892. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  5893. closeBridgeModal();
  5894. loadBridge();
  5895. fetchData(false);
  5896. } else {
  5897. const err = await res.json();
  5898. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  5899. }
  5900. } catch (err) {
  5901. showToast('Error', err.message, 'error');
  5902. }
  5903. }
  5904. async function toggleBridgeState(id, disabled) {
  5905. try {
  5906. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  5907. method: 'POST',
  5908. headers: { 'Content-Type': 'application/json' },
  5909. body: JSON.stringify({ disabled })
  5910. });
  5911. if (res.ok) {
  5912. loadBridge();
  5913. fetchData(false);
  5914. }
  5915. } catch (err) {
  5916. showToast('Error', err.message, 'error');
  5917. }
  5918. }
  5919. async function deleteBridge(id) {
  5920. const b = (state.bridges || []).find(x => x.id === id);
  5921. const name = b ? b.name : id;
  5922. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  5923. try {
  5924. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5925. if (res.ok) {
  5926. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  5927. loadBridge();
  5928. fetchData(false);
  5929. } else {
  5930. const err = await res.json();
  5931. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  5932. }
  5933. } catch (err) {
  5934. showToast('Error', err.message, 'error');
  5935. }
  5936. }
  5937. // ----------------- Bridge IP Assignments -----------------
  5938. function openAddBridgeIPModal(id, name) {
  5939. document.getElementById('bridge-ip-modal-id').value = id;
  5940. document.getElementById('bridge-ip-modal-sub').innerText = name;
  5941. document.getElementById('bridge-ip-modal-cidr').value = '';
  5942. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  5943. }
  5944. function closeBridgeIPModal() {
  5945. document.getElementById('bridge-ip-modal').classList.add('hidden');
  5946. }
  5947. async function submitAddBridgeIP(e) {
  5948. e.preventDefault();
  5949. const id = document.getElementById('bridge-ip-modal-id').value;
  5950. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  5951. try {
  5952. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  5953. method: 'POST',
  5954. headers: { 'Content-Type': 'application/json' },
  5955. body: JSON.stringify({ ip })
  5956. });
  5957. if (res.ok) {
  5958. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  5959. closeBridgeIPModal();
  5960. loadBridge();
  5961. fetchData(false);
  5962. } else {
  5963. const err = await res.json();
  5964. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  5965. }
  5966. } catch (err) {
  5967. showToast('Error', err.message, 'error');
  5968. }
  5969. }
  5970. async function deleteBridgeIP(id, ip) {
  5971. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  5972. try {
  5973. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  5974. method: 'DELETE',
  5975. headers: { 'Content-Type': 'application/json' },
  5976. body: JSON.stringify({ ip })
  5977. });
  5978. if (res.ok) {
  5979. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  5980. loadBridge();
  5981. fetchData(false);
  5982. }
  5983. } catch (err) {
  5984. showToast('Error', err.message, 'error');
  5985. }
  5986. }
  5987. // ----------------- Bridge Ports -----------------
  5988. function renderBridgePorts() {
  5989. const tbody = document.getElementById('bridge-ports-table-body');
  5990. const empty = document.getElementById('bridge-empty-ports');
  5991. const countBadge = document.getElementById('bridge-ports-count-badge');
  5992. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  5993. if (!tbody) return;
  5994. tbody.innerHTML = '';
  5995. // Update filter select
  5996. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  5997. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  5998. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  5999. if (ports.length === 0) {
  6000. empty?.classList.remove('hidden');
  6001. return;
  6002. }
  6003. empty?.classList.add('hidden');
  6004. ports.forEach((p, idx) => {
  6005. const tr = document.createElement('tr');
  6006. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  6007. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  6008. tr.innerHTML = `
  6009. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  6010. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  6011. <td class="py-2.5 px-3 font-bold text-white text-sm">
  6012. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  6013. </td>
  6014. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  6015. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  6016. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  6017. <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>
  6018. <td class="py-2.5 px-3">
  6019. ${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>'}
  6020. </td>
  6021. <td class="py-2.5 px-3">
  6022. <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>
  6023. </td>
  6024. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  6025. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6026. <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>
  6027. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6028. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6029. </td>
  6030. `;
  6031. tbody.appendChild(tr);
  6032. });
  6033. }
  6034. function openAddBridgePortModal() {
  6035. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  6036. document.getElementById('bridge-port-modal-id').value = '';
  6037. populateBridgeSelect('bridge-port-modal-bridge');
  6038. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  6039. document.getElementById('bridge-port-modal-pvid').value = '1';
  6040. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  6041. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  6042. document.getElementById('bridge-port-modal-horizon').value = '0';
  6043. document.getElementById('bridge-port-modal-pathcost').value = '10';
  6044. document.getElementById('bridge-port-modal-priority').value = '128';
  6045. document.getElementById('bridge-port-modal-learn').checked = true;
  6046. document.getElementById('bridge-port-modal-comment').value = '';
  6047. document.getElementById('bridge-port-modal-disabled').checked = false;
  6048. document.getElementById('bridge-port-modal').classList.remove('hidden');
  6049. }
  6050. function openEditBridgePortModal(id) {
  6051. const p = (state.bridgePorts || []).find(x => x.id === id);
  6052. if (!p) return;
  6053. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  6054. document.getElementById('bridge-port-modal-id').value = p.id;
  6055. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  6056. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  6057. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  6058. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  6059. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  6060. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  6061. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  6062. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  6063. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  6064. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  6065. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  6066. document.getElementById('bridge-port-modal').classList.remove('hidden');
  6067. }
  6068. function closeBridgePortModal() {
  6069. document.getElementById('bridge-port-modal').classList.add('hidden');
  6070. }
  6071. async function submitSaveBridgePort(e) {
  6072. e.preventDefault();
  6073. const id = document.getElementById('bridge-port-modal-id').value;
  6074. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  6075. const iface = document.getElementById('bridge-port-modal-interface').value;
  6076. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  6077. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  6078. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  6079. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  6080. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  6081. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  6082. const learn = document.getElementById('bridge-port-modal-learn').checked;
  6083. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  6084. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  6085. try {
  6086. const res = await fetch(`${API_BASE}/bridge/ports`, {
  6087. method: 'POST',
  6088. headers: { 'Content-Type': 'application/json' },
  6089. body: JSON.stringify({
  6090. id,
  6091. bridge,
  6092. interface: iface,
  6093. pvid,
  6094. frame_types: frameTypes,
  6095. ingress_filtering: ingressFiltering,
  6096. horizon,
  6097. path_cost: pathCost,
  6098. priority,
  6099. learn,
  6100. comment,
  6101. disabled
  6102. })
  6103. });
  6104. if (res.ok) {
  6105. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  6106. closeBridgePortModal();
  6107. loadBridge();
  6108. fetchData(false);
  6109. } else {
  6110. const err = await res.json();
  6111. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  6112. }
  6113. } catch (err) {
  6114. showToast('Error', err.message, 'error');
  6115. }
  6116. }
  6117. async function toggleBridgePortState(id, disabled) {
  6118. try {
  6119. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  6120. method: 'POST',
  6121. headers: { 'Content-Type': 'application/json' },
  6122. body: JSON.stringify({ disabled })
  6123. });
  6124. if (res.ok) {
  6125. loadBridge();
  6126. fetchData(false);
  6127. }
  6128. } catch (err) {
  6129. showToast('Error', err.message, 'error');
  6130. }
  6131. }
  6132. async function deleteBridgePort(id) {
  6133. const p = (state.bridgePorts || []).find(x => x.id === id);
  6134. const iface = p ? p.interface : id;
  6135. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  6136. try {
  6137. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6138. if (res.ok) {
  6139. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  6140. loadBridge();
  6141. fetchData(false);
  6142. }
  6143. } catch (err) {
  6144. showToast('Error', err.message, 'error');
  6145. }
  6146. }
  6147. // ----------------- Bridge VLANs -----------------
  6148. function renderBridgeVLANs() {
  6149. const tbody = document.getElementById('bridge-vlans-table-body');
  6150. const empty = document.getElementById('bridge-empty-vlans');
  6151. const countBadge = document.getElementById('bridge-vlans-count-badge');
  6152. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  6153. if (!tbody) return;
  6154. tbody.innerHTML = '';
  6155. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  6156. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  6157. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  6158. if (vlans.length === 0) {
  6159. empty?.classList.remove('hidden');
  6160. return;
  6161. }
  6162. empty?.classList.add('hidden');
  6163. vlans.forEach((v, idx) => {
  6164. const tr = document.createElement('tr');
  6165. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  6166. const taggedHtml = (v.tagged && v.tagged.length > 0)
  6167. ? 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(' ')
  6168. : '<span class="text-slate-600">none</span>';
  6169. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  6170. ? 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(' ')
  6171. : '<span class="text-slate-600">none</span>';
  6172. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  6173. tr.innerHTML = `
  6174. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  6175. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  6176. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  6177. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  6178. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  6179. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  6180. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  6181. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6182. <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>
  6183. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6184. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6185. </td>
  6186. `;
  6187. tbody.appendChild(tr);
  6188. });
  6189. }
  6190. function openAddBridgeVLANModal() {
  6191. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  6192. document.getElementById('bridge-vlan-modal-id').value = '';
  6193. populateBridgeSelect('bridge-vlan-modal-bridge');
  6194. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  6195. document.getElementById('bridge-vlan-modal-comment').value = '';
  6196. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  6197. updateBridgeVlanPortCheckboxes();
  6198. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  6199. }
  6200. function openEditBridgeVLANModal(id) {
  6201. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  6202. if (!v) return;
  6203. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  6204. document.getElementById('bridge-vlan-modal-id').value = v.id;
  6205. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  6206. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  6207. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  6208. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  6209. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  6210. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  6211. }
  6212. function closeBridgeVlanModal() {
  6213. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  6214. }
  6215. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  6216. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  6217. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  6218. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  6219. if (!taggedBox || !untaggedBox) return;
  6220. // Ports belonging to the selected bridge
  6221. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  6222. if (memberPorts.length === 0) {
  6223. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  6224. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  6225. return;
  6226. }
  6227. taggedBox.innerHTML = memberPorts.map(p => `
  6228. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  6229. <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">
  6230. <span>${p.interface}</span>
  6231. </label>
  6232. `).join('');
  6233. untaggedBox.innerHTML = memberPorts.map(p => `
  6234. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  6235. <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">
  6236. <span>${p.interface}</span>
  6237. </label>
  6238. `).join('');
  6239. }
  6240. async function submitSaveBridgeVLAN(e) {
  6241. e.preventDefault();
  6242. const id = document.getElementById('bridge-vlan-modal-id').value;
  6243. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  6244. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  6245. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  6246. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  6247. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  6248. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  6249. try {
  6250. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  6251. method: 'POST',
  6252. headers: { 'Content-Type': 'application/json' },
  6253. body: JSON.stringify({
  6254. id,
  6255. bridge,
  6256. vlan_ids: vlanIDs,
  6257. tagged,
  6258. untagged,
  6259. comment,
  6260. disabled
  6261. })
  6262. });
  6263. if (res.ok) {
  6264. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  6265. closeBridgeVlanModal();
  6266. loadBridge();
  6267. } else {
  6268. const err = await res.json();
  6269. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  6270. }
  6271. } catch (err) {
  6272. showToast('Error', err.message, 'error');
  6273. }
  6274. }
  6275. async function toggleBridgeVLANState(id, disabled) {
  6276. try {
  6277. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  6278. method: 'POST',
  6279. headers: { 'Content-Type': 'application/json' },
  6280. body: JSON.stringify({ disabled })
  6281. });
  6282. if (res.ok) loadBridge();
  6283. } catch (err) {
  6284. showToast('Error', err.message, 'error');
  6285. }
  6286. }
  6287. async function deleteBridgeVLAN(id) {
  6288. if (!confirm('Delete this bridge VLAN entry?')) return;
  6289. try {
  6290. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6291. if (res.ok) {
  6292. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  6293. loadBridge();
  6294. }
  6295. } catch (err) {
  6296. showToast('Error', err.message, 'error');
  6297. }
  6298. }
  6299. // ----------------- Hosts / MAC Table -----------------
  6300. async function loadBridgeHosts() {
  6301. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  6302. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  6303. try {
  6304. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  6305. const res = await fetch(url);
  6306. if (res.ok) {
  6307. state.bridgeHosts = await res.json();
  6308. renderBridgeHosts();
  6309. }
  6310. } catch (err) {
  6311. console.error('Failed to load bridge hosts:', err);
  6312. }
  6313. }
  6314. function renderBridgeHosts() {
  6315. const tbody = document.getElementById('bridge-hosts-table-body');
  6316. const empty = document.getElementById('bridge-empty-hosts');
  6317. const countBadge = document.getElementById('bridge-hosts-count-badge');
  6318. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  6319. if (!tbody) return;
  6320. tbody.innerHTML = '';
  6321. const hosts = (state.bridgeHosts || []).filter(h => {
  6322. if (!search) return true;
  6323. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  6324. });
  6325. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  6326. if (hosts.length === 0) {
  6327. empty?.classList.remove('hidden');
  6328. return;
  6329. }
  6330. empty?.classList.add('hidden');
  6331. hosts.forEach(h => {
  6332. const tr = document.createElement('tr');
  6333. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  6334. let flagBadges = '';
  6335. 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>';
  6336. 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>';
  6337. 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>';
  6338. tr.innerHTML = `
  6339. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  6340. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  6341. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  6342. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  6343. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  6344. <td class="py-2.5 px-3">${flagBadges}</td>
  6345. `;
  6346. tbody.appendChild(tr);
  6347. });
  6348. }
  6349. async function flushBridgeHosts() {
  6350. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  6351. if (!selBridge) {
  6352. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  6353. return;
  6354. }
  6355. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  6356. try {
  6357. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  6358. method: 'POST',
  6359. headers: { 'Content-Type': 'application/json' },
  6360. body: JSON.stringify({ bridge: selBridge })
  6361. });
  6362. if (res.ok) {
  6363. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  6364. loadBridgeHosts();
  6365. }
  6366. } catch (err) {
  6367. showToast('Error', err.message, 'error');
  6368. }
  6369. }
  6370. // ----------------- Helpers -----------------
  6371. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  6372. const sel = document.getElementById(selectId);
  6373. if (!sel) return;
  6374. const prevVal = currentVal || sel.value;
  6375. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  6376. (state.bridges || []).forEach(b => {
  6377. const opt = document.createElement('option');
  6378. opt.value = b.name;
  6379. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  6380. if (b.name === prevVal) opt.selected = true;
  6381. sel.appendChild(opt);
  6382. });
  6383. }
  6384. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  6385. const sel = document.getElementById(selectId);
  6386. if (!sel) return;
  6387. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  6388. // 1. Physical Interfaces
  6389. const grpPhys = document.createElement('optgroup');
  6390. grpPhys.label = 'Physical Interfaces';
  6391. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  6392. const opt = document.createElement('option');
  6393. opt.value = i.name;
  6394. opt.innerText = `${i.name} (${i.role || i.type})`;
  6395. if (i.name === currentVal) opt.selected = true;
  6396. grpPhys.appendChild(opt);
  6397. });
  6398. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  6399. // 2. VLAN Sub-interfaces
  6400. const grpVlans = document.createElement('optgroup');
  6401. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  6402. (state.vlans || []).forEach(v => {
  6403. const opt = document.createElement('option');
  6404. opt.value = v.name;
  6405. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  6406. if (v.name === currentVal) opt.selected = true;
  6407. grpVlans.appendChild(opt);
  6408. });
  6409. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  6410. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  6411. const grpEoip = document.createElement('optgroup');
  6412. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  6413. (state.eoipTunnels || []).forEach(t => {
  6414. const opt = document.createElement('option');
  6415. opt.value = t.name;
  6416. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  6417. if (t.name === currentVal) opt.selected = true;
  6418. grpEoip.appendChild(opt);
  6419. });
  6420. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  6421. }
  6422. // -------------------------------------------------------------
  6423. // Routing Filters Management (/routing filter)
  6424. // -------------------------------------------------------------
  6425. function renderRoutingFilters() {
  6426. const tbody = document.getElementById('routing-filters-table-body');
  6427. if (!tbody) return;
  6428. const empty = document.getElementById('routing-filters-empty');
  6429. const countBadge = document.getElementById('routing-filters-count-badge');
  6430. const navBadge = document.getElementById('badge-filters-count');
  6431. const chainSelect = document.getElementById('routing-filter-chain-select');
  6432. const allRules = state.routingFilters || [];
  6433. if (navBadge) navBadge.innerText = allRules.length;
  6434. // Populate chain filter select options dynamically
  6435. if (chainSelect) {
  6436. const currentVal = state.filterChainSelected || 'all';
  6437. const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
  6438. chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
  6439. uniqueChains.map(ch => {
  6440. const count = allRules.filter(r => r.chain === ch).length;
  6441. return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
  6442. }).join('');
  6443. chainSelect.value = currentVal;
  6444. }
  6445. // Filter rules by selected chain
  6446. const filteredRules = (state.filterChainSelected && state.filterChainSelected !== 'all')
  6447. ? allRules.filter(r => r.chain === state.filterChainSelected)
  6448. : allRules.slice();
  6449. // Sort by chain then rule_order
  6450. filteredRules.sort((a, b) => {
  6451. if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
  6452. return (a.rule_order || 0) - (b.rule_order || 0);
  6453. });
  6454. if (countBadge) countBadge.innerText = `${filteredRules.length} Rules`;
  6455. if (filteredRules.length === 0) {
  6456. tbody.innerHTML = '';
  6457. if (empty) empty.classList.remove('hidden');
  6458. return;
  6459. }
  6460. if (empty) empty.classList.add('hidden');
  6461. tbody.innerHTML = filteredRules.map(r => {
  6462. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  6463. const flagX = r.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  6464. let actionBadge = '';
  6465. if (r.action === 'accept') {
  6466. 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>';
  6467. } else if (r.action === 'discard') {
  6468. 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>';
  6469. } else if (r.action === 'reject') {
  6470. 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>';
  6471. } else {
  6472. 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>`;
  6473. }
  6474. // Prefix match
  6475. let matchPfx = '';
  6476. if (r.prefix) {
  6477. matchPfx = `<span class="font-bold text-white">${escapeHtml(r.prefix)}</span>`;
  6478. if (r.prefix_len) {
  6479. matchPfx += ` <span class="text-slate-400 text-[11px] font-normal">[${escapeHtml(r.prefix_len)}]</span>`;
  6480. }
  6481. } else {
  6482. matchPfx = '<span class="text-slate-500 italic">any prefix</span>';
  6483. }
  6484. // Other matches
  6485. const matchExtra = [];
  6486. if (r.match_protocol && r.match_protocol !== 'any') {
  6487. 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>`);
  6488. }
  6489. if (r.match_as_path) {
  6490. 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>`);
  6491. }
  6492. if (r.match_community) {
  6493. 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>`);
  6494. }
  6495. const matchExtraHtml = matchExtra.length > 0 ? matchExtra.join(' ') : '<span class="text-slate-600">-</span>';
  6496. // Set modifications
  6497. const setBadges = [];
  6498. if (r.set_local_pref > 0) {
  6499. 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>`);
  6500. }
  6501. if (r.set_metric > 0) {
  6502. 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>`);
  6503. }
  6504. if (r.set_as_prepend > 0) {
  6505. 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>`);
  6506. }
  6507. if (r.set_community) {
  6508. 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>`);
  6509. }
  6510. if (r.set_next_hop) {
  6511. 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>`);
  6512. }
  6513. const setHtml = setBadges.length > 0 ? setBadges.join(' ') : '<span class="text-slate-600">-</span>';
  6514. return `
  6515. <tr class="hover:bg-slate-800/40 transition">
  6516. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagX}</td>
  6517. <td class="py-2.5 px-3 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  6518. <td class="py-2.5 px-3">
  6519. <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>
  6520. </td>
  6521. <td class="py-2.5 px-3">${actionBadge}</td>
  6522. <td class="py-2.5 px-3 font-mono">${matchPfx}</td>
  6523. <td class="py-2.5 px-3 space-x-1">${matchExtraHtml}</td>
  6524. <td class="py-2.5 px-3 space-x-1 font-mono">${setHtml}</td>
  6525. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  6526. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  6527. <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'}">
  6528. ${r.disabled ? 'Enable' : 'Disable'}
  6529. </button>
  6530. <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">
  6531. Edit
  6532. </button>
  6533. <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">
  6534. Delete
  6535. </button>
  6536. </td>
  6537. </tr>
  6538. `;
  6539. }).join('');
  6540. }
  6541. function filterRoutingFiltersByChain(chain) {
  6542. state.filterChainSelected = chain;
  6543. renderRoutingFilters();
  6544. }
  6545. function openAddRoutingFilterModal(defaultChain = '') {
  6546. const form = document.getElementById('routing-filter-form');
  6547. if (form) form.reset();
  6548. const idEl = document.getElementById('modal-rf-id');
  6549. if (idEl) idEl.value = '';
  6550. const titleEl = document.getElementById('modal-rf-title');
  6551. if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
  6552. const chainEl = document.getElementById('modal-rf-chain');
  6553. if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
  6554. const orderEl = document.getElementById('modal-rf-order');
  6555. if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
  6556. const actEl = document.getElementById('modal-rf-action');
  6557. if (actEl) actEl.value = 'accept';
  6558. const protoEl = document.getElementById('modal-rf-protocol');
  6559. if (protoEl) protoEl.value = 'any';
  6560. const disEl = document.getElementById('modal-rf-disabled');
  6561. if (disEl) disEl.checked = false;
  6562. const modal = document.getElementById('modal-routing-filter');
  6563. if (modal) modal.classList.remove('hidden');
  6564. }
  6565. function openEditRoutingFilterModal(id) {
  6566. const r = (state.routingFilters || []).find(item => item.id === id);
  6567. if (!r) return;
  6568. const idEl = document.getElementById('modal-rf-id');
  6569. if (idEl) idEl.value = r.id;
  6570. const titleEl = document.getElementById('modal-rf-title');
  6571. if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
  6572. const chainEl = document.getElementById('modal-rf-chain');
  6573. if (chainEl) chainEl.value = r.chain || '';
  6574. const orderEl = document.getElementById('modal-rf-order');
  6575. if (orderEl) orderEl.value = r.rule_order || 10;
  6576. const actEl = document.getElementById('modal-rf-action');
  6577. if (actEl) actEl.value = r.action || 'accept';
  6578. const pfxEl = document.getElementById('modal-rf-prefix');
  6579. if (pfxEl) pfxEl.value = r.prefix || '';
  6580. const pfxLenEl = document.getElementById('modal-rf-prefix-len');
  6581. if (pfxLenEl) pfxLenEl.value = r.prefix_len || '';
  6582. const protoEl = document.getElementById('modal-rf-protocol');
  6583. if (protoEl) protoEl.value = r.match_protocol || 'any';
  6584. const aspEl = document.getElementById('modal-rf-as-path');
  6585. if (aspEl) aspEl.value = r.match_as_path || '';
  6586. const commEl = document.getElementById('modal-rf-community');
  6587. if (commEl) commEl.value = r.match_community || '';
  6588. const lpEl = document.getElementById('modal-rf-set-local-pref');
  6589. if (lpEl) lpEl.value = r.set_local_pref || '';
  6590. const metEl = document.getElementById('modal-rf-set-metric');
  6591. if (metEl) metEl.value = r.set_metric || '';
  6592. const prepEl = document.getElementById('modal-rf-set-as-prepend');
  6593. if (prepEl) prepEl.value = r.set_as_prepend || '';
  6594. const setCommEl = document.getElementById('modal-rf-set-community');
  6595. if (setCommEl) setCommEl.value = r.set_community || '';
  6596. const nhEl = document.getElementById('modal-rf-set-next-hop');
  6597. if (nhEl) nhEl.value = r.set_next_hop || '';
  6598. const comEl = document.getElementById('modal-rf-comment');
  6599. if (comEl) comEl.value = r.comment || '';
  6600. const disEl = document.getElementById('modal-rf-disabled');
  6601. if (disEl) disEl.checked = !!r.disabled;
  6602. const modal = document.getElementById('modal-routing-filter');
  6603. if (modal) modal.classList.remove('hidden');
  6604. }
  6605. function closeRoutingFilterModal() {
  6606. const modal = document.getElementById('modal-routing-filter');
  6607. if (modal) modal.classList.add('hidden');
  6608. }
  6609. async function submitRoutingFilter(e) {
  6610. e.preventDefault();
  6611. const payload = {
  6612. id: document.getElementById('modal-rf-id').value,
  6613. chain: document.getElementById('modal-rf-chain').value.trim(),
  6614. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  6615. action: document.getElementById('modal-rf-action').value,
  6616. prefix: document.getElementById('modal-rf-prefix').value.trim(),
  6617. prefix_len: document.getElementById('modal-rf-prefix-len').value.trim(),
  6618. match_protocol: document.getElementById('modal-rf-protocol').value,
  6619. match_as_path: document.getElementById('modal-rf-as-path').value.trim(),
  6620. match_community: document.getElementById('modal-rf-community').value.trim(),
  6621. set_local_pref: parseInt(document.getElementById('modal-rf-set-local-pref').value, 10) || 0,
  6622. set_metric: parseInt(document.getElementById('modal-rf-set-metric').value, 10) || 0,
  6623. set_as_prepend: parseInt(document.getElementById('modal-rf-set-as-prepend').value, 10) || 0,
  6624. set_community: document.getElementById('modal-rf-set-community').value.trim(),
  6625. set_next_hop: document.getElementById('modal-rf-set-next-hop').value.trim(),
  6626. comment: document.getElementById('modal-rf-comment').value.trim(),
  6627. disabled: document.getElementById('modal-rf-disabled').checked
  6628. };
  6629. try {
  6630. const res = await fetch(`${API_BASE}/routing/filters`, {
  6631. method: 'POST',
  6632. headers: { 'Content-Type': 'application/json' },
  6633. body: JSON.stringify(payload)
  6634. });
  6635. if (res.ok) {
  6636. closeRoutingFilterModal();
  6637. showToast('Success', 'Routing filter rule saved', 'success');
  6638. loadDynamicRouting();
  6639. } else {
  6640. const err = await res.json();
  6641. showToast('Error', err.error || 'Failed to save filter rule', 'error');
  6642. }
  6643. } catch (err) {
  6644. showToast('Error', err.message, 'error');
  6645. }
  6646. }
  6647. async function deleteRoutingFilter(id) {
  6648. if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
  6649. try {
  6650. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6651. if (res.ok) {
  6652. showToast('Deleted', 'Routing filter rule removed', 'info');
  6653. loadDynamicRouting();
  6654. } else {
  6655. const err = await res.json();
  6656. showToast('Error', err.error || 'Failed to delete rule', 'error');
  6657. }
  6658. } catch (err) {
  6659. showToast('Error', err.message, 'error');
  6660. }
  6661. }
  6662. async function toggleRoutingFilterState(id, disabled) {
  6663. try {
  6664. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
  6665. method: 'POST',
  6666. headers: { 'Content-Type': 'application/json' },
  6667. body: JSON.stringify({ disabled })
  6668. });
  6669. if (res.ok) {
  6670. showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  6671. loadDynamicRouting();
  6672. } else {
  6673. const err = await res.json();
  6674. showToast('Error', err.error || 'Failed to toggle rule state', 'error');
  6675. }
  6676. } catch (err) {
  6677. showToast('Error', err.message, 'error');
  6678. }
  6679. }
  6680. // ==========================================
  6681. // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
  6682. // ==========================================
  6683. function loadToolsView() {
  6684. populateToolsInterfaces();
  6685. switchToolsSubTab(state.activeToolsSubTab || 'ping');
  6686. }
  6687. function populateToolsInterfaces() {
  6688. const pingSel = document.getElementById('tools-ping-iface');
  6689. const traceSel = document.getElementById('tools-tr-iface');
  6690. let opts = '<option value="">Auto (Default Route)</option>';
  6691. if (Array.isArray(state.interfaces)) {
  6692. state.interfaces.forEach(iface => {
  6693. if (iface.name) {
  6694. opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
  6695. }
  6696. });
  6697. }
  6698. if (pingSel) {
  6699. const cur = pingSel.value;
  6700. pingSel.innerHTML = opts;
  6701. if (cur) pingSel.value = cur;
  6702. }
  6703. if (traceSel) {
  6704. const cur = traceSel.value;
  6705. traceSel.innerHTML = opts;
  6706. if (cur) traceSel.value = cur;
  6707. }
  6708. }
  6709. function switchToolsSubTab(subTab) {
  6710. state.activeToolsSubTab = subTab;
  6711. const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
  6712. tabs.forEach(t => {
  6713. const btn = document.getElementById(`tools-subtab-btn-${t}`);
  6714. const view = document.getElementById(`tools-view-${t}`);
  6715. if (btn) {
  6716. if (t === subTab) {
  6717. 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';
  6718. } else {
  6719. 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';
  6720. }
  6721. }
  6722. if (view) {
  6723. if (t === subTab) {
  6724. view.classList.remove('hidden');
  6725. } else {
  6726. view.classList.add('hidden');
  6727. }
  6728. }
  6729. });
  6730. }
  6731. function setPortPreset(port) {
  6732. const input = document.getElementById('tools-port-num');
  6733. if (input) input.value = port;
  6734. }
  6735. let pingAbortController = null;
  6736. let tracerouteAbortController = null;
  6737. function clearPingTable() {
  6738. const tbody = document.getElementById('tools-ping-tbody');
  6739. if (tbody) tbody.innerHTML = '';
  6740. const rawEl = document.getElementById('tools-ping-raw');
  6741. if (rawEl) rawEl.innerText = '';
  6742. const sentEl = document.getElementById('tools-ping-stat-sent');
  6743. if (sentEl) sentEl.innerText = '0';
  6744. const recvEl = document.getElementById('tools-ping-stat-recv');
  6745. if (recvEl) recvEl.innerText = '0';
  6746. const lossEl = document.getElementById('tools-ping-stat-loss');
  6747. if (lossEl) lossEl.innerText = '0%';
  6748. const avgEl = document.getElementById('tools-ping-stat-avg');
  6749. if (avgEl) avgEl.innerText = '0 ms';
  6750. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  6751. if (minMaxEl) minMaxEl.innerText = '-';
  6752. const badge = document.getElementById('tools-ping-status-badge');
  6753. if (badge) {
  6754. badge.className = '';
  6755. badge.innerText = '';
  6756. }
  6757. }
  6758. function clearTracerouteTable() {
  6759. const tbody = document.getElementById('tools-tr-tbody');
  6760. if (tbody) tbody.innerHTML = '';
  6761. const rawEl = document.getElementById('tools-tr-raw');
  6762. if (rawEl) rawEl.innerText = '';
  6763. const statHops = document.getElementById('tools-tr-hops-count');
  6764. if (statHops) statHops.innerText = '0 Hops';
  6765. }
  6766. function resetPingButton() {
  6767. const btn = document.getElementById('tools-ping-btn');
  6768. const btnText = document.getElementById('tools-ping-btn-text');
  6769. const spinner = document.getElementById('tools-ping-spinner');
  6770. if (btn) {
  6771. btn.disabled = false;
  6772. 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';
  6773. }
  6774. if (btnText) btnText.innerText = 'Start Ping';
  6775. if (spinner) spinner.classList.add('hidden');
  6776. }
  6777. function setPingRunningButton() {
  6778. const btn = document.getElementById('tools-ping-btn');
  6779. const btnText = document.getElementById('tools-ping-btn-text');
  6780. const spinner = document.getElementById('tools-ping-spinner');
  6781. if (btn) {
  6782. btn.disabled = false;
  6783. 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';
  6784. }
  6785. if (btnText) btnText.innerText = 'Stop Ping';
  6786. if (spinner) spinner.classList.remove('hidden');
  6787. }
  6788. function resetTracerouteButton() {
  6789. const btn = document.getElementById('tools-tr-btn');
  6790. const btnText = document.getElementById('tools-tr-btn-text');
  6791. const spinner = document.getElementById('tools-tr-spinner');
  6792. if (btn) {
  6793. btn.disabled = false;
  6794. 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';
  6795. }
  6796. if (btnText) btnText.innerText = 'Start Traceroute';
  6797. if (spinner) spinner.classList.add('hidden');
  6798. }
  6799. function setTracerouteRunningButton() {
  6800. const btn = document.getElementById('tools-tr-btn');
  6801. const btnText = document.getElementById('tools-tr-btn-text');
  6802. const spinner = document.getElementById('tools-tr-spinner');
  6803. if (btn) {
  6804. btn.disabled = false;
  6805. 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';
  6806. }
  6807. if (btnText) btnText.innerText = 'Stop Traceroute';
  6808. if (spinner) spinner.classList.remove('hidden');
  6809. }
  6810. async function executePing(e) {
  6811. if (e) e.preventDefault();
  6812. // If already running, clicking the button stops the stream!
  6813. if (pingAbortController) {
  6814. pingAbortController.abort();
  6815. pingAbortController = null;
  6816. resetPingButton();
  6817. showToast('Ping Stopped', 'Live ping stopped by user', 'info');
  6818. return;
  6819. }
  6820. const target = document.getElementById('tools-ping-target')?.value?.trim();
  6821. const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
  6822. const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
  6823. const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '3', 10);
  6824. const iface = document.getElementById('tools-ping-iface')?.value || '';
  6825. const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
  6826. if (!target) {
  6827. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  6828. return;
  6829. }
  6830. clearPingTable();
  6831. const resCard = document.getElementById('tools-ping-results');
  6832. if (resCard) resCard.classList.remove('hidden');
  6833. pingAbortController = new AbortController();
  6834. setPingRunningButton();
  6835. try {
  6836. const res = await fetch(`${API_BASE}/tools/ping/stream`, {
  6837. method: 'POST',
  6838. headers: { 'Content-Type': 'application/json' },
  6839. body: JSON.stringify({
  6840. target,
  6841. count,
  6842. size,
  6843. timeout,
  6844. interface: iface,
  6845. dont_frag: dontFrag
  6846. }),
  6847. signal: pingAbortController.signal
  6848. });
  6849. if (!res.ok) {
  6850. const errText = await res.text();
  6851. showToast('Ping Error', errText || 'Failed to start live ping', 'error');
  6852. resetPingButton();
  6853. pingAbortController = null;
  6854. return;
  6855. }
  6856. const reader = res.body.getReader();
  6857. const decoder = new TextDecoder('utf-8');
  6858. let buffer = '';
  6859. while (true) {
  6860. const { done, value } = await reader.read();
  6861. if (done) break;
  6862. buffer += decoder.decode(value, { stream: true });
  6863. const blocks = buffer.split('\n\n');
  6864. buffer = blocks.pop() || '';
  6865. for (const block of blocks) {
  6866. const trimmed = block.trim();
  6867. if (!trimmed) continue;
  6868. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  6869. try {
  6870. const evt = JSON.parse(line);
  6871. handleLivePingEvent(evt);
  6872. } catch (parseErr) {
  6873. console.warn('Ping SSE parse error:', parseErr, line);
  6874. }
  6875. }
  6876. }
  6877. } catch (err) {
  6878. if (err.name === 'AbortError') {
  6879. // User aborted normally
  6880. } else {
  6881. showToast('Ping Error', err.message, 'error');
  6882. }
  6883. } finally {
  6884. pingAbortController = null;
  6885. resetPingButton();
  6886. }
  6887. }
  6888. function handleLivePingEvent(evt) {
  6889. const sentEl = document.getElementById('tools-ping-stat-sent');
  6890. const recvEl = document.getElementById('tools-ping-stat-recv');
  6891. const lossEl = document.getElementById('tools-ping-stat-loss');
  6892. const avgEl = document.getElementById('tools-ping-stat-avg');
  6893. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  6894. const badge = document.getElementById('tools-ping-status-badge');
  6895. const tbody = document.getElementById('tools-ping-tbody');
  6896. const rawEl = document.getElementById('tools-ping-raw');
  6897. if (evt.raw && rawEl) {
  6898. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  6899. rawEl.scrollTop = rawEl.scrollHeight;
  6900. }
  6901. if (evt.type === 'reply') {
  6902. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  6903. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  6904. if (lossEl && evt.packet_loss_pct !== undefined) {
  6905. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  6906. lossEl.className = evt.packet_loss_pct === 0
  6907. ? 'text-base font-bold font-mono text-emerald-400 mt-1'
  6908. : (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');
  6909. }
  6910. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  6911. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  6912. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  6913. }
  6914. if (badge) {
  6915. if (evt.packet_loss_pct === 0) {
  6916. 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';
  6917. badge.innerText = '100% OK';
  6918. } else {
  6919. 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';
  6920. badge.innerText = `${evt.packet_loss_pct.toFixed(0)}% LOSS`;
  6921. }
  6922. }
  6923. if (tbody) {
  6924. const tr = document.createElement('tr');
  6925. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  6926. tr.innerHTML = `
  6927. <td class="py-2 px-3 text-slate-300">#${evt.seq}</td>
  6928. <td class="py-2 px-3 font-semibold text-white">${escapeHtml(evt.from)}</td>
  6929. <td class="py-2 px-3 text-slate-400">${evt.bytes} bytes</td>
  6930. <td class="py-2 px-3 text-slate-300">${evt.ttl}</td>
  6931. <td class="py-2 px-3 font-bold text-amber-300">${evt.time_ms.toFixed(2)} ms</td>
  6932. <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>
  6933. `;
  6934. tbody.appendChild(tr);
  6935. }
  6936. } else if (evt.type === 'timeout') {
  6937. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  6938. if (lossEl && evt.packet_loss_pct !== undefined) {
  6939. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  6940. 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';
  6941. }
  6942. if (badge) {
  6943. 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';
  6944. badge.innerText = `${evt.packet_loss_pct?.toFixed(0) || 100}% LOSS`;
  6945. }
  6946. if (tbody) {
  6947. const tr = document.createElement('tr');
  6948. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs opacity-75';
  6949. tr.innerHTML = `
  6950. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  6951. <td class="py-2 px-3 font-semibold text-slate-500 italic">Request timed out</td>
  6952. <td class="py-2 px-3 text-slate-600">--</td>
  6953. <td class="py-2 px-3 text-slate-600">--</td>
  6954. <td class="py-2 px-3 font-bold text-slate-500">* * *</td>
  6955. <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>
  6956. `;
  6957. tbody.appendChild(tr);
  6958. }
  6959. } else if (evt.type === 'unreach') {
  6960. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  6961. if (lossEl && evt.packet_loss_pct !== undefined) {
  6962. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  6963. lossEl.className = 'text-base font-bold font-mono text-rose-400 mt-1';
  6964. }
  6965. if (badge) {
  6966. 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';
  6967. badge.innerText = 'UNREACHABLE';
  6968. }
  6969. if (tbody) {
  6970. const tr = document.createElement('tr');
  6971. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  6972. tr.innerHTML = `
  6973. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  6974. <td class="py-2 px-3 font-semibold text-rose-400">${escapeHtml(evt.from || 'Gateway')}</td>
  6975. <td class="py-2 px-3 text-slate-600">--</td>
  6976. <td class="py-2 px-3 text-slate-600">--</td>
  6977. <td class="py-2 px-3 font-bold text-rose-400 text-xs">${escapeHtml(evt.message || 'Unreachable')}</td>
  6978. <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>
  6979. `;
  6980. tbody.appendChild(tr);
  6981. }
  6982. } else if (evt.type === 'stats') {
  6983. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  6984. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  6985. if (lossEl && evt.packet_loss_pct !== undefined) lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  6986. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  6987. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  6988. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  6989. }
  6990. } else if (evt.type === 'done') {
  6991. 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');
  6992. }
  6993. }
  6994. async function executeTraceroute(e) {
  6995. if (e) e.preventDefault();
  6996. if (tracerouteAbortController) {
  6997. tracerouteAbortController.abort();
  6998. tracerouteAbortController = null;
  6999. resetTracerouteButton();
  7000. showToast('Traceroute Stopped', 'Traceroute stopped by user', 'info');
  7001. return;
  7002. }
  7003. const target = document.getElementById('tools-tr-target')?.value?.trim();
  7004. const maxHops = parseInt(document.getElementById('tools-tr-maxhops')?.value || '15', 10);
  7005. const protocol = document.getElementById('tools-tr-proto')?.value || 'icmp';
  7006. const iface = document.getElementById('tools-tr-iface')?.value || '';
  7007. const resolve = document.getElementById('tools-tr-resolve')?.checked || false;
  7008. if (!target) {
  7009. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  7010. return;
  7011. }
  7012. clearTracerouteTable();
  7013. const resCard = document.getElementById('tools-tr-results');
  7014. if (resCard) resCard.classList.remove('hidden');
  7015. tracerouteAbortController = new AbortController();
  7016. setTracerouteRunningButton();
  7017. try {
  7018. const res = await fetch(`${API_BASE}/tools/traceroute/stream`, {
  7019. method: 'POST',
  7020. headers: { 'Content-Type': 'application/json' },
  7021. body: JSON.stringify({
  7022. target,
  7023. max_hops: maxHops,
  7024. protocol,
  7025. interface: iface,
  7026. resolve
  7027. }),
  7028. signal: tracerouteAbortController.signal
  7029. });
  7030. if (!res.ok) {
  7031. const errText = await res.text();
  7032. showToast('Traceroute Error', errText || 'Failed to start traceroute', 'error');
  7033. resetTracerouteButton();
  7034. tracerouteAbortController = null;
  7035. return;
  7036. }
  7037. const reader = res.body.getReader();
  7038. const decoder = new TextDecoder('utf-8');
  7039. let buffer = '';
  7040. while (true) {
  7041. const { done, value } = await reader.read();
  7042. if (done) break;
  7043. buffer += decoder.decode(value, { stream: true });
  7044. const blocks = buffer.split('\n\n');
  7045. buffer = blocks.pop() || '';
  7046. for (const block of blocks) {
  7047. const trimmed = block.trim();
  7048. if (!trimmed) continue;
  7049. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  7050. try {
  7051. const evt = JSON.parse(line);
  7052. handleLiveTracerouteEvent(evt);
  7053. } catch (parseErr) {
  7054. console.warn('Traceroute SSE parse error:', parseErr, line);
  7055. }
  7056. }
  7057. }
  7058. } catch (err) {
  7059. if (err.name === 'AbortError') {
  7060. // User aborted normally
  7061. } else {
  7062. showToast('Traceroute Error', err.message, 'error');
  7063. }
  7064. } finally {
  7065. tracerouteAbortController = null;
  7066. resetTracerouteButton();
  7067. }
  7068. }
  7069. function handleLiveTracerouteEvent(evt) {
  7070. const statHops = document.getElementById('tools-tr-hops-count');
  7071. const tbody = document.getElementById('tools-tr-tbody');
  7072. const rawEl = document.getElementById('tools-tr-raw');
  7073. if (evt.raw && rawEl) {
  7074. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  7075. rawEl.scrollTop = rawEl.scrollHeight;
  7076. }
  7077. if (evt.hops_count !== undefined && statHops) {
  7078. statHops.innerText = `${evt.hops_count} Hops`;
  7079. }
  7080. if (evt.type === 'hop' && evt.hop && tbody) {
  7081. const h = evt.hop;
  7082. const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
  7083. const rtt1 = Array.isArray(h.times_ms) && h.times_ms[0] ? `${h.times_ms[0]} ms` : (isTimeout ? '*' : '--');
  7084. const rtt2 = Array.isArray(h.times_ms) && h.times_ms[1] ? `${h.times_ms[1]} ms` : (isTimeout ? '*' : '--');
  7085. const displayHost = h.host && h.host !== h.ip ? `${escapeHtml(h.host)} (${escapeHtml(h.ip || '')})` : escapeHtml(h.ip || (isTimeout ? 'Request timed out' : '--'));
  7086. const tr = document.createElement('tr');
  7087. tr.className = `hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}`;
  7088. tr.innerHTML = `
  7089. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  7090. <td class="py-2.5 px-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${displayHost}</td>
  7091. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt1)}</td>
  7092. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt2)}</td>
  7093. <td class="py-2.5 px-3 text-right">
  7094. ${isTimeout
  7095. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
  7096. : '<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>'}
  7097. </td>
  7098. `;
  7099. tbody.appendChild(tr);
  7100. } else if (evt.type === 'done') {
  7101. showToast('Traceroute Finished', `Traced ${evt.hops_count || 0} hops`, 'info');
  7102. }
  7103. }
  7104. async function executeMTR(e) {
  7105. if (e) e.preventDefault();
  7106. const target = document.getElementById('tools-mtr-target')?.value?.trim();
  7107. const cycles = parseInt(document.getElementById('tools-mtr-count')?.value || '3', 10);
  7108. if (!target) {
  7109. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  7110. return;
  7111. }
  7112. const btn = document.getElementById('tools-mtr-btn');
  7113. const spinner = document.getElementById('tools-mtr-spinner');
  7114. if (btn) btn.disabled = true;
  7115. if (spinner) spinner.classList.remove('hidden');
  7116. try {
  7117. const res = await fetch(`${API_BASE}/tools/mtr`, {
  7118. method: 'POST',
  7119. headers: { 'Content-Type': 'application/json' },
  7120. body: JSON.stringify({ target, count: cycles })
  7121. });
  7122. const data = await res.json();
  7123. if (!res.ok) {
  7124. showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
  7125. return;
  7126. }
  7127. const resCard = document.getElementById('tools-mtr-results');
  7128. if (resCard) resCard.classList.remove('hidden');
  7129. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  7130. const statHops = document.getElementById('tools-mtr-hops-count');
  7131. if (statHops) statHops.innerText = `${hopsCount} Hops`;
  7132. const tbody = document.getElementById('tools-mtr-tbody');
  7133. if (tbody) {
  7134. if (hopsCount > 0) {
  7135. tbody.innerHTML = data.hops.map(h => {
  7136. 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');
  7137. return `
  7138. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  7139. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  7140. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
  7141. <td class="py-2.5 px-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
  7142. <td class="py-2.5 px-3 text-slate-300">${h.sent}</td>
  7143. <td class="py-2.5 px-3 text-slate-300">${h.last_ms.toFixed(1)}</td>
  7144. <td class="py-2.5 px-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)}</td>
  7145. <td class="py-2.5 px-3 text-emerald-400">${h.best_ms.toFixed(1)}</td>
  7146. <td class="py-2.5 px-3 text-rose-400">${h.wrst_ms.toFixed(1)}</td>
  7147. <td class="py-2.5 px-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
  7148. </tr>
  7149. `;
  7150. }).join('');
  7151. } else {
  7152. tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
  7153. }
  7154. }
  7155. const rawEl = document.getElementById('tools-mtr-raw');
  7156. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  7157. showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
  7158. } catch (err) {
  7159. showToast('MTR Error', err.message, 'error');
  7160. } finally {
  7161. if (btn) btn.disabled = false;
  7162. if (spinner) spinner.classList.add('hidden');
  7163. }
  7164. }
  7165. async function executeDNS(e) {
  7166. if (e) e.preventDefault();
  7167. const domain = document.getElementById('tools-dns-domain')?.value?.trim();
  7168. const type = document.getElementById('tools-dns-type')?.value || 'A';
  7169. const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
  7170. if (!domain) {
  7171. showToast('Input Required', 'Please enter a hostname or domain', 'warning');
  7172. return;
  7173. }
  7174. const btn = document.getElementById('tools-dns-btn');
  7175. const spinner = document.getElementById('tools-dns-spinner');
  7176. if (btn) btn.disabled = true;
  7177. if (spinner) spinner.classList.remove('hidden');
  7178. try {
  7179. const res = await fetch(`${API_BASE}/tools/dns`, {
  7180. method: 'POST',
  7181. headers: { 'Content-Type': 'application/json' },
  7182. body: JSON.stringify({ domain, type, server })
  7183. });
  7184. const data = await res.json();
  7185. if (!res.ok) {
  7186. showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
  7187. return;
  7188. }
  7189. const resCard = document.getElementById('tools-dns-results');
  7190. if (resCard) resCard.classList.remove('hidden');
  7191. const metaEl = document.getElementById('tools-dns-meta');
  7192. if (metaEl) metaEl.innerText = `Resolved in ${data.query_time_ms ?? 0} ms via ${escapeHtml(data.server || 'System DNS')}`;
  7193. const tbody = document.getElementById('tools-dns-tbody');
  7194. if (tbody) {
  7195. if (Array.isArray(data.records) && data.records.length > 0) {
  7196. tbody.innerHTML = data.records.map(r => `
  7197. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  7198. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.name)}</td>
  7199. <td class="py-2.5 px-3 text-slate-400">${r.ttl}s</td>
  7200. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.class || 'IN')}</td>
  7201. <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>
  7202. <td class="py-2.5 px-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
  7203. </tr>
  7204. `).join('');
  7205. } else {
  7206. 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>`;
  7207. }
  7208. }
  7209. const rawEl = document.getElementById('tools-dns-raw');
  7210. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  7211. showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
  7212. } catch (err) {
  7213. showToast('DNS Error', err.message, 'error');
  7214. } finally {
  7215. if (btn) btn.disabled = false;
  7216. if (spinner) spinner.classList.add('hidden');
  7217. }
  7218. }
  7219. async function executePortProbe(e) {
  7220. if (e) e.preventDefault();
  7221. const target = document.getElementById('tools-port-target')?.value?.trim();
  7222. const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
  7223. const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
  7224. if (!target || !port) {
  7225. showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
  7226. return;
  7227. }
  7228. const btn = document.getElementById('tools-port-btn');
  7229. const spinner = document.getElementById('tools-port-spinner');
  7230. if (btn) btn.disabled = true;
  7231. if (spinner) spinner.classList.remove('hidden');
  7232. try {
  7233. const res = await fetch(`${API_BASE}/tools/port-probe`, {
  7234. method: 'POST',
  7235. headers: { 'Content-Type': 'application/json' },
  7236. body: JSON.stringify({ target, port, timeout })
  7237. });
  7238. const data = await res.json();
  7239. if (!res.ok) {
  7240. showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
  7241. return;
  7242. }
  7243. const resCard = document.getElementById('tools-port-results');
  7244. if (resCard) resCard.classList.remove('hidden');
  7245. const banner = document.getElementById('tools-port-banner');
  7246. const icon = document.getElementById('tools-port-icon');
  7247. const title = document.getElementById('tools-port-title');
  7248. const sub = document.getElementById('tools-port-sub');
  7249. const latency = document.getElementById('tools-port-latency');
  7250. if (data.open) {
  7251. if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
  7252. if (icon) {
  7253. 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';
  7254. icon.innerText = '✓';
  7255. }
  7256. if (title) {
  7257. title.className = 'text-sm font-bold text-emerald-300';
  7258. title.innerText = `PORT ${port} OPEN / LISTENING`;
  7259. }
  7260. if (sub) {
  7261. sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
  7262. sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
  7263. }
  7264. if (latency) {
  7265. latency.className = 'text-base font-bold font-mono text-emerald-300';
  7266. latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
  7267. }
  7268. } else {
  7269. if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-800/50 flex items-center justify-between';
  7270. if (icon) {
  7271. 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';
  7272. icon.innerText = '✕';
  7273. }
  7274. if (title) {
  7275. title.className = 'text-sm font-bold text-rose-300';
  7276. title.innerText = `PORT ${port} CLOSED / FILTERED`;
  7277. }
  7278. if (sub) {
  7279. sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
  7280. sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
  7281. }
  7282. if (latency) {
  7283. latency.className = 'text-base font-bold font-mono text-slate-500';
  7284. latency.innerText = '--';
  7285. }
  7286. }
  7287. const rawEl = document.getElementById('tools-port-raw');
  7288. 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'}`);
  7289. showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
  7290. } catch (err) {
  7291. showToast('Probe Error', err.message, 'error');
  7292. } finally {
  7293. if (btn) btn.disabled = false;
  7294. if (spinner) spinner.classList.add('hidden');
  7295. }
  7296. }
  7297. // ==========================================
  7298. // DHCP CLIENT (/ip dhcp-client) CONTROLLER
  7299. // ==========================================
  7300. async function loadDHCPClients(showToastMsg = false) {
  7301. try {
  7302. const [clientsRes, sumRes] = await Promise.all([
  7303. fetch(`${API_BASE}/dhcp/clients`),
  7304. fetch(`${API_BASE}/dhcp/clients/summary`)
  7305. ]);
  7306. if (clientsRes.ok) {
  7307. state.dhcpClients = await clientsRes.json();
  7308. }
  7309. if (sumRes.ok) {
  7310. state.dhcpSummary = await sumRes.json();
  7311. }
  7312. renderDHCPClients();
  7313. updateDHCPSummaryCards();
  7314. const bDhcp = document.getElementById('badge-dhcp-client-count');
  7315. if (bDhcp && state.dhcpSummary) {
  7316. bDhcp.innerText = state.dhcpSummary.total_clients || 0;
  7317. }
  7318. if (showToastMsg) {
  7319. showToast('Refreshed', 'DHCP Client telemetry updated', 'info');
  7320. }
  7321. } catch (err) {
  7322. console.error('Failed to load DHCP clients:', err);
  7323. if (showToastMsg) {
  7324. showToast('Notice', 'Unable to fetch DHCP client status', 'warning');
  7325. }
  7326. }
  7327. }
  7328. function updateDHCPSummaryCards() {
  7329. const sum = state.dhcpSummary || {
  7330. total_clients: (state.dhcpClients || []).length,
  7331. bound_clients: (state.dhcpClients || []).filter(c => c.status === 'bound').length,
  7332. searching_clients: (state.dhcpClients || []).filter(c => c.status === 'searching').length,
  7333. disabled_clients: (state.dhcpClients || []).filter(c => !c.enabled).length
  7334. };
  7335. const totalEl = document.getElementById('dhcp-stat-total');
  7336. const boundEl = document.getElementById('dhcp-stat-bound');
  7337. const searchEl = document.getElementById('dhcp-stat-searching');
  7338. const disEl = document.getElementById('dhcp-stat-disabled');
  7339. if (totalEl) totalEl.innerText = sum.total_clients ?? 0;
  7340. if (boundEl) boundEl.innerText = sum.bound_clients ?? 0;
  7341. if (searchEl) searchEl.innerText = sum.searching_clients ?? 0;
  7342. if (disEl) disEl.innerText = sum.disabled_clients ?? 0;
  7343. }
  7344. function renderDHCPClients() {
  7345. const tbody = document.getElementById('dhcp-clients-tbody');
  7346. const emptyState = document.getElementById('dhcp-clients-empty');
  7347. if (!tbody) return;
  7348. const clients = Array.isArray(state.dhcpClients) ? state.dhcpClients : [];
  7349. if (clients.length === 0) {
  7350. tbody.innerHTML = '';
  7351. if (emptyState) emptyState.classList.remove('hidden');
  7352. return;
  7353. }
  7354. if (emptyState) emptyState.classList.add('hidden');
  7355. tbody.innerHTML = clients.map(c => {
  7356. let statusBadge = '';
  7357. if (!c.enabled) {
  7358. 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>';
  7359. } else if (c.status === 'bound') {
  7360. 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>';
  7361. } else if (c.status === 'searching') {
  7362. 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>';
  7363. } else if (c.status === 'stopped') {
  7364. 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>';
  7365. } else {
  7366. 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>`;
  7367. }
  7368. 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>';
  7369. const gwDisplay = c.gateway ? `<span class="text-slate-300">${escapeHtml(c.gateway)}</span>` : '<span class="text-slate-600">--</span>';
  7370. const srvDisplay = c.dhcp_server ? `<span class="text-slate-300">${escapeHtml(c.dhcp_server)}</span>` : '<span class="text-slate-600">--</span>';
  7371. 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>';
  7372. const expDisplay = c.expires_in ? `<span class="text-purple-300">${escapeHtml(c.expires_in)}</span>` : '<span class="text-slate-600">--</span>';
  7373. // Option flags
  7374. const flags = [];
  7375. 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>');
  7376. 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>');
  7377. 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>');
  7378. 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>`);
  7379. return `
  7380. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 text-xs transition">
  7381. <td class="py-3 px-4">
  7382. <div class="flex items-center gap-2">
  7383. <span class="font-bold text-white text-sm">${escapeHtml(c.interface)}</span>
  7384. ${c.comment ? `<span class="text-[11px] text-slate-400 font-sans italic">(${escapeHtml(c.comment)})</span>` : ''}
  7385. </div>
  7386. </td>
  7387. <td class="py-3 px-4">${statusBadge}</td>
  7388. <td class="py-3 px-4 font-mono">${ipDisplay}</td>
  7389. <td class="py-3 px-4 font-mono">${gwDisplay}</td>
  7390. <td class="py-3 px-4 font-mono">${srvDisplay}</td>
  7391. <td class="py-3 px-4 font-mono text-[11px]">${dnsDisplay}</td>
  7392. <td class="py-3 px-4 font-mono text-[11px]">${expDisplay}</td>
  7393. <td class="py-3 px-4">
  7394. <div class="flex flex-wrap gap-1 font-mono">${flags.join('')}</div>
  7395. </td>
  7396. <td class="py-3 px-4 text-right space-x-1.5 font-sans whitespace-nowrap">
  7397. ${c.enabled ? `
  7398. <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>
  7399. <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>
  7400. <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>
  7401. ` : `
  7402. <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>
  7403. `}
  7404. <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>
  7405. <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>
  7406. </td>
  7407. </tr>
  7408. `;
  7409. }).join('');
  7410. }
  7411. function openDHCPClientModal(clientId = null) {
  7412. const modal = document.getElementById('modal-dhcp-client');
  7413. if (!modal) return;
  7414. const title = document.getElementById('modal-dhcp-title');
  7415. const idInput = document.getElementById('modal-dhcp-id');
  7416. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  7417. const distInput = document.getElementById('modal-dhcp-distance');
  7418. const commentInput = document.getElementById('modal-dhcp-comment');
  7419. const defRouteCheck = document.getElementById('modal-dhcp-def-route');
  7420. const peerDnsCheck = document.getElementById('modal-dhcp-peer-dns');
  7421. const peerNtpCheck = document.getElementById('modal-dhcp-peer-ntp');
  7422. const enabledCheck = document.getElementById('modal-dhcp-enabled');
  7423. // Populate interfaces
  7424. if (ifaceSelect) {
  7425. let opts = '<option value="">Select interface...</option>';
  7426. const allIfaces = state.interfaces || [];
  7427. const allVlans = state.vlans || [];
  7428. const usedIfaces = new Set((state.dhcpClients || []).map(c => c.interface));
  7429. // Group 1: Physical & Bridge Interfaces
  7430. opts += '<optgroup label="Physical & Bridge Interfaces">';
  7431. allIfaces.forEach(i => {
  7432. const isConfigured = usedIfaces.has(i.name) ? ' (Configured)' : '';
  7433. opts += `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} [${escapeHtml(i.role || i.type)}]${isConfigured}</option>`;
  7434. });
  7435. opts += '</optgroup>';
  7436. // Group 2: VLAN Interfaces
  7437. if (allVlans.length > 0) {
  7438. opts += '<optgroup label="802.1Q VLAN Sub-interfaces">';
  7439. allVlans.forEach(v => {
  7440. const isConfigured = usedIfaces.has(v.name) ? ' (Configured)' : '';
  7441. opts += `<option value="${escapeHtml(v.name)}">${escapeHtml(v.name)} (VLAN ${v.vlan_id})${isConfigured}</option>`;
  7442. });
  7443. opts += '</optgroup>';
  7444. }
  7445. ifaceSelect.innerHTML = opts;
  7446. }
  7447. if (clientId) {
  7448. const client = (state.dhcpClients || []).find(c => c.id === clientId);
  7449. if (client) {
  7450. if (title) title.innerText = `Edit DHCP Client: ${client.interface}`;
  7451. if (idInput) idInput.value = client.id;
  7452. if (ifaceSelect) {
  7453. ifaceSelect.value = client.interface;
  7454. ifaceSelect.disabled = true; // interface cannot be changed on edit
  7455. }
  7456. if (distInput) distInput.value = client.default_route_distance || 1;
  7457. if (commentInput) commentInput.value = client.comment || '';
  7458. if (defRouteCheck) defRouteCheck.checked = client.add_default_route !== false;
  7459. if (peerDnsCheck) peerDnsCheck.checked = client.use_peer_dns !== false;
  7460. if (peerNtpCheck) peerNtpCheck.checked = client.use_peer_ntp !== false;
  7461. if (enabledCheck) enabledCheck.checked = client.enabled !== false;
  7462. }
  7463. } else {
  7464. if (title) title.innerText = 'Add DHCP Client';
  7465. if (idInput) idInput.value = '';
  7466. if (ifaceSelect) {
  7467. ifaceSelect.value = '';
  7468. ifaceSelect.disabled = false;
  7469. }
  7470. if (distInput) distInput.value = 1;
  7471. if (commentInput) commentInput.value = '';
  7472. if (defRouteCheck) defRouteCheck.checked = true;
  7473. if (peerDnsCheck) peerDnsCheck.checked = true;
  7474. if (peerNtpCheck) peerNtpCheck.checked = true;
  7475. if (enabledCheck) enabledCheck.checked = true;
  7476. }
  7477. modal.classList.remove('hidden');
  7478. }
  7479. function openDHCPClientModalForIface(ifaceName) {
  7480. openDHCPClientModal();
  7481. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  7482. if (ifaceSelect && ifaceName) {
  7483. ifaceSelect.value = ifaceName;
  7484. }
  7485. }
  7486. function closeDHCPClientModal() {
  7487. const modal = document.getElementById('modal-dhcp-client');
  7488. if (modal) modal.classList.add('hidden');
  7489. }
  7490. async function submitSaveDHCPClient(e) {
  7491. if (e) e.preventDefault();
  7492. const id = document.getElementById('modal-dhcp-id')?.value;
  7493. const iface = document.getElementById('modal-dhcp-iface')?.value?.trim();
  7494. const distance = parseInt(document.getElementById('modal-dhcp-distance')?.value || '1', 10);
  7495. const comment = document.getElementById('modal-dhcp-comment')?.value?.trim() || '';
  7496. const defRoute = document.getElementById('modal-dhcp-def-route')?.checked ?? true;
  7497. const peerDns = document.getElementById('modal-dhcp-peer-dns')?.checked ?? true;
  7498. const peerNtp = document.getElementById('modal-dhcp-peer-ntp')?.checked ?? true;
  7499. const enabled = document.getElementById('modal-dhcp-enabled')?.checked ?? true;
  7500. if (!id && !iface) {
  7501. showToast('Input Required', 'Please select an interface for the DHCP client', 'warning');
  7502. return;
  7503. }
  7504. try {
  7505. let res;
  7506. if (id) {
  7507. // PUT update
  7508. res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  7509. method: 'PUT',
  7510. headers: { 'Content-Type': 'application/json' },
  7511. body: JSON.stringify({
  7512. enabled,
  7513. add_default_route: defRoute,
  7514. default_route_distance: distance,
  7515. use_peer_dns: peerDns,
  7516. use_peer_ntp: peerNtp,
  7517. comment
  7518. })
  7519. });
  7520. } else {
  7521. // POST create
  7522. res = await fetch(`${API_BASE}/dhcp/clients`, {
  7523. method: 'POST',
  7524. headers: { 'Content-Type': 'application/json' },
  7525. body: JSON.stringify({
  7526. interface: iface,
  7527. enabled,
  7528. add_default_route: defRoute,
  7529. default_route_distance: distance,
  7530. use_peer_dns: peerDns,
  7531. use_peer_ntp: peerNtp,
  7532. comment
  7533. })
  7534. });
  7535. }
  7536. const data = await res.json();
  7537. if (!res.ok) {
  7538. showToast('Error', data.error || 'Failed to save DHCP client', 'error');
  7539. return;
  7540. }
  7541. closeDHCPClientModal();
  7542. showToast('Success', id ? 'DHCP Client updated successfully' : `DHCP Client activated on ${iface}`, 'success');
  7543. await loadDHCPClients();
  7544. fetchData(); // refresh interfaces list with new lease/status
  7545. } catch (err) {
  7546. showToast('Error', err.message, 'error');
  7547. }
  7548. }
  7549. async function toggleDHCPClientState(id, enabled) {
  7550. try {
  7551. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/state`, {
  7552. method: 'POST',
  7553. headers: { 'Content-Type': 'application/json' },
  7554. body: JSON.stringify({ enabled })
  7555. });
  7556. const data = await res.json();
  7557. if (!res.ok) {
  7558. showToast('Error', data.error || 'Failed to toggle client state', 'error');
  7559. return;
  7560. }
  7561. showToast('Updated', `DHCP client ${enabled ? 'enabled' : 'disabled'}`, 'info');
  7562. await loadDHCPClients();
  7563. fetchData();
  7564. } catch (err) {
  7565. showToast('Error', err.message, 'error');
  7566. }
  7567. }
  7568. async function renewDHCPClient(id) {
  7569. try {
  7570. showToast('Renewing...', 'Requesting DHCP lease renewal from upstream server', 'info');
  7571. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/renew`, {
  7572. method: 'POST'
  7573. });
  7574. const data = await res.json();
  7575. if (!res.ok) {
  7576. showToast('Error', data.error || 'Failed to renew lease', 'error');
  7577. return;
  7578. }
  7579. showToast('Lease Renewed', 'DHCP renewal signal sent successfully', 'success');
  7580. setTimeout(() => {
  7581. loadDHCPClients();
  7582. fetchData();
  7583. }, 1500);
  7584. } catch (err) {
  7585. showToast('Error', err.message, 'error');
  7586. }
  7587. }
  7588. async function releaseDHCPClient(id) {
  7589. try {
  7590. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/release`, {
  7591. method: 'POST'
  7592. });
  7593. const data = await res.json();
  7594. if (!res.ok) {
  7595. showToast('Error', data.error || 'Failed to release lease', 'error');
  7596. return;
  7597. }
  7598. showToast('Lease Released', 'DHCP lease released from upstream server', 'info');
  7599. await loadDHCPClients();
  7600. fetchData();
  7601. } catch (err) {
  7602. showToast('Error', err.message, 'error');
  7603. }
  7604. }
  7605. async function deleteDHCPClient(id, ifaceName) {
  7606. if (!confirm(`Are you sure you want to remove the DHCP Client on ${ifaceName}? The interface will release its dynamic IP.`)) {
  7607. return;
  7608. }
  7609. try {
  7610. const res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  7611. method: 'DELETE'
  7612. });
  7613. const data = await res.json();
  7614. if (!res.ok) {
  7615. showToast('Error', data.error || 'Failed to delete DHCP client', 'error');
  7616. return;
  7617. }
  7618. showToast('Deleted', `DHCP client removed from ${ifaceName}`, 'info');
  7619. await loadDHCPClients();
  7620. fetchData();
  7621. } catch (err) {
  7622. showToast('Error', err.message, 'error');
  7623. }
  7624. }