app.js 497 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968
  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. initTableSorting();
  64. fetchData();
  65. // Live polling every 2.5 seconds
  66. setInterval(() => {
  67. if (state.isPolling) {
  68. fetchData(false);
  69. }
  70. }, 2500);
  71. });
  72. // Navigation Handler
  73. function navigate(tabName) {
  74. if (tabName === 'dynamic-routing' || tabName === 'routing') {
  75. navigate('bgp');
  76. return;
  77. }
  78. if (tabName === 'vlans') {
  79. navigate('interfaces');
  80. return;
  81. }
  82. state.activeTab = tabName;
  83. window.location.hash = tabName;
  84. // Update nav links styling
  85. document.querySelectorAll('.nav-link').forEach(link => {
  86. 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';
  87. });
  88. const activeNav = document.getElementById(`nav-${tabName}`);
  89. if (activeNav) {
  90. 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';
  91. }
  92. // Update page headers
  93. const titles = {
  94. dashboard: { title: 'Dashboard Overview', sub: 'Live router performance and network telemetry' },
  95. interfaces: { title: 'Network Interfaces', sub: 'Interface Table View' },
  96. 'dhcp-client': { title: 'DHCP Client', sub: 'DHCP Client List' },
  97. bridge: { title: 'Bridge Interfaces', sub: 'IEEE 802.1D / 802.1Q VLAN-aware Layer 2 switching, RSTP & hardware forwarding (FDB)' },
  98. vlans: { title: 'VLAN Virtual Networks', sub: 'IEEE 802.1Q sub-interface segmentation and routing' },
  99. firewall: { title: 'Network Firewall', sub: 'Stateful packet inspection, NAT, traffic mangle, address lists & connection tracking' },
  100. routes: { title: 'Routing & Policy', sub: 'Routing tables, static routes (DAS/DAC), and policy routing rules' },
  101. bgp: { title: 'BGP Routing (/routing bgp)', sub: 'BIRD 2 BGP Multi-Instance peering sessions, advertised networks, and BGP routing table (RIB)' },
  102. ospf: { title: 'OSPF Routing (/routing ospf)', sub: 'BIRD 2 OSPFv2 link-state routing, dynamic neighbor adjacencies, and multi-area topology' },
  103. 'routing-filters': { title: 'Routing Filters (/routing filter)', sub: 'Route filter chains, prefix matching, BGP community maps & policy-based path control' },
  104. 'dynamic-routing': { title: 'BGP Routing (/routing bgp)', sub: 'BIRD 2 dynamic routing engine' },
  105. ppp: { title: 'PPP Servers & Secrets', sub: 'Subscriber authentication, dynamic IP pools and VPN access concentrators' },
  106. eoip: { title: 'EoIP Tunnels', sub: 'Ethernet over IP (EoIP / GRETAP) Layer 2 encapsulation & transparent network bridging' },
  107. pppoe: { title: 'PPPoE Client WAN', sub: 'Point-to-Point Protocol over Ethernet WAN access' },
  108. wireguard: { title: 'WireGuard VPN', sub: 'High-performance cryptographic Layer 3 tunnels with ChaCha20-Poly1305 key exchange' },
  109. ipsec: { title: 'IPSec (IKEv2) strongSwan', sub: 'Enterprise Site-to-Site & Roadwarrior IPSec controller' },
  110. l2tp: { title: 'L2TP VPN Client', sub: 'Layer 2 Tunneling Protocol via xl2tpd' },
  111. pptp: { title: 'PPTP VPN Client', sub: 'Point-to-Point Tunneling Protocol with MPPE-128 encryption' },
  112. tools: { title: 'Diagnostic & Troubleshooting Tools', sub: 'Network latency analysis, ICMP/MTR telemetry, path tracing, DNS resolution and TCP probing' },
  113. persistence: { title: 'Debian Configuration', sub: 'Native /etc/network/interfaces.d/ persistence manager' }
  114. };
  115. const header = titles[tabName] || titles.dashboard;
  116. const pTitle = document.getElementById('page-title');
  117. if (pTitle) pTitle.innerText = header.title;
  118. const pSub = document.getElementById('page-subtitle');
  119. if (pSub) pSub.innerText = header.sub;
  120. // Toggle sections dynamically for all section elements
  121. document.querySelectorAll('main section[id^="section-"]').forEach(el => {
  122. if (el.id === `section-${tabName}`) {
  123. el.classList.remove('hidden');
  124. } else {
  125. el.classList.add('hidden');
  126. }
  127. });
  128. if (tabName === 'bridge') loadBridge();
  129. if (tabName === 'firewall') loadFirewall();
  130. if (tabName === 'routes') loadRoutes();
  131. if (tabName === 'bgp') {
  132. loadDynamicRouting();
  133. switchBgpSubTab(state.activeBgpSubTab || 'bgp-peers');
  134. }
  135. if (tabName === 'ospf') {
  136. loadDynamicRouting();
  137. switchOspfTab(state.activeOspfTab || 'instances');
  138. }
  139. if (tabName === 'routing-filters') loadDynamicRouting();
  140. if (tabName === 'dynamic-routing') loadDynamicRouting();
  141. if (tabName === 'ppp') loadPPP();
  142. if (tabName === 'eoip') loadEoIP();
  143. if (tabName === 'persistence') loadDebianConfig();
  144. if (tabName === 'pppoe') loadPPPoE();
  145. if (tabName === 'wireguard') loadWireGuard();
  146. if (tabName === 'ipsec') loadIPSec();
  147. if (tabName === 'l2tp') loadL2TP();
  148. if (tabName === 'pptp') loadPPTP();
  149. if (tabName === 'tools') loadToolsView();
  150. if (tabName === 'dhcp-client') loadDHCPClients();
  151. setTimeout(initTableSorting, 50);
  152. }
  153. // Fetch all core system, network and VPN telemetry
  154. async function fetchData(isManual = false) {
  155. const spinner = document.getElementById('refresh-spinner');
  156. if (isManual && spinner) spinner.classList.add('animate-spin');
  157. try {
  158. const [statusRes, ifacesRes, vlansRes, vpnRes, fwRes, dynRes, brSummaryRes, dhcpSumRes, dhcpClientsRes] = await Promise.all([
  159. fetch(`${API_BASE}/system/status`),
  160. fetch(`${API_BASE}/interfaces`),
  161. fetch(`${API_BASE}/vlans`),
  162. fetch(`${API_BASE}/vpn/status`),
  163. fetch(`${API_BASE}/firewall/summary`),
  164. fetch(`${API_BASE}/routing/dynamic/summary`),
  165. fetch(`${API_BASE}/bridge/summary`),
  166. fetch(`${API_BASE}/dhcp/clients/summary`),
  167. fetch(`${API_BASE}/dhcp/clients`)
  168. ]);
  169. if (dhcpSumRes && dhcpSumRes.ok) {
  170. state.dhcpSummary = await dhcpSumRes.json();
  171. const bDhcp = document.getElementById('badge-dhcp-client-count');
  172. if (bDhcp) bDhcp.innerText = state.dhcpSummary?.total_clients || 0;
  173. }
  174. if (dhcpClientsRes && dhcpClientsRes.ok) {
  175. state.dhcpClients = await dhcpClientsRes.json();
  176. }
  177. if (brSummaryRes.ok) {
  178. state.bridgeSummary = await brSummaryRes.json();
  179. const bBridge = document.getElementById('badge-bridge-count');
  180. if (bBridge) bBridge.innerText = state.bridgeSummary?.bridges_count || 0;
  181. const sBr = document.getElementById('bridge-stat-bridges');
  182. if (sBr) sBr.innerText = state.bridgeSummary?.bridges_count || 0;
  183. const sPorts = document.getElementById('bridge-stat-ports');
  184. if (sPorts) sPorts.innerText = state.bridgeSummary?.ports_count || 0;
  185. const sHosts = document.getElementById('bridge-stat-hosts');
  186. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  187. }
  188. if (statusRes.ok) state.systemStatus = await statusRes.json();
  189. if (ifacesRes.ok) {
  190. const ifacesData = await ifacesRes.json();
  191. const rawIfaces = Array.isArray(ifacesData) ? ifacesData : [];
  192. state.interfaces = rawIfaces.filter(i => {
  193. if (!i.name) return false;
  194. if (i.name.startsWith('ep_')) return false;
  195. return !['gre0', 'gretap0', 'erspan0', 'sit0', 'tunl0', 'ip6tnl0', 'ip6gre0', 'ip6erspan0'].includes(i.name);
  196. });
  197. try { populateToolsInterfaces(); } catch (e) {}
  198. }
  199. if (vlansRes.ok) {
  200. const vlansData = await vlansRes.json();
  201. state.vlans = Array.isArray(vlansData) ? vlansData : [];
  202. }
  203. if (vpnRes.ok) state.vpnStatus = await vpnRes.json();
  204. if (fwRes && fwRes.ok) state.fwSummary = await fwRes.json();
  205. if (dynRes && dynRes.ok) state.dynSummary = await dynRes.json();
  206. updateSystemMetrics();
  207. updateBadges();
  208. if (state.activeTab === 'dashboard') renderDashboard();
  209. if (state.activeTab === 'interfaces') renderInterfacesList();
  210. if (state.activeTab === 'vlans') renderVlansList();
  211. if (state.activeTab === 'firewall') loadFirewall(false);
  212. if (state.activeTab === 'routes') loadRoutes(false);
  213. if (state.activeTab === 'dynamic-routing' || state.activeTab === 'bgp' || state.activeTab === 'ospf') loadDynamicRouting(false);
  214. if (state.activeTab === 'ppp') loadPPP(false);
  215. if (state.activeTab === 'eoip') loadEoIP(false);
  216. if (state.activeTab === 'pppoe') loadPPPoE(false);
  217. if (state.activeTab === 'wireguard') loadWireGuard(false);
  218. if (state.activeTab === 'ipsec') loadIPSec(false);
  219. if (state.activeTab === 'l2tp') loadL2TP(false);
  220. if (state.activeTab === 'pptp') loadPPTP(false);
  221. if (state.activeTab === 'dhcp-client') loadDHCPClients(false);
  222. } catch (err) {
  223. console.error('Failed to fetch router state:', err);
  224. } finally {
  225. if (isManual && spinner) {
  226. setTimeout(() => spinner.classList.remove('animate-spin'), 300);
  227. }
  228. }
  229. }
  230. // Update Top KPI and Sidebar Telemetry
  231. function updateSystemMetrics() {
  232. const s = state.systemStatus;
  233. const v = state.vpnStatus;
  234. if (!s) return;
  235. // Sidebar Host & Uptime
  236. const sideHost = document.getElementById('side-hostname');
  237. if (sideHost) sideHost.innerText = s.hostname || 'debian-lxc';
  238. const sideUp = document.getElementById('side-uptime');
  239. if (sideUp) sideUp.innerText = s.uptime_human || '0m';
  240. const sideGw = document.getElementById('side-gateway-ip');
  241. if (sideGw) sideGw.innerText = s.default_gateway ? `GW: ${s.default_gateway}` : 'GW: Isolated';
  242. // Compute CPU Metrics
  243. let cpuPct = 0;
  244. if (s.cpu_pct !== undefined) {
  245. cpuPct = s.cpu_pct;
  246. } else if (s.cpu_load && s.cpu_load.length > 0) {
  247. const cores = s.cpu_cores || 1;
  248. cpuPct = Math.min(100, Math.round((parseFloat(s.cpu_load[0]) / cores) * 100));
  249. }
  250. const cpuPctStr = `${cpuPct.toFixed(1)}%`;
  251. const cpuWidth = `${Math.max(3, Math.min(100, cpuPct))}%`;
  252. const loadStr = s.cpu_load ? s.cpu_load.join(', ') : '-';
  253. // Sidebar CPU
  254. const sideCpuVal = document.getElementById('side-cpu-val');
  255. if (sideCpuVal) sideCpuVal.innerText = cpuPctStr;
  256. const sideCpuBar = document.getElementById('side-cpu-bar');
  257. if (sideCpuBar) {
  258. sideCpuBar.style.width = cpuWidth;
  259. sideCpuBar.title = `Container: ${cpuPctStr} | Host Loadavg: ${loadStr} (${s.cpu_cores || 1} cores)`;
  260. }
  261. // Dashboard CPU Card
  262. const dashCpuVal = document.getElementById('dash-cpu-val');
  263. if (dashCpuVal) dashCpuVal.innerText = cpuPctStr;
  264. const dashCpuBar = document.getElementById('dash-cpu-bar');
  265. if (dashCpuBar) {
  266. dashCpuBar.style.width = cpuWidth;
  267. if (cpuPct > 85) {
  268. dashCpuBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  269. } else if (cpuPct > 65) {
  270. dashCpuBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  271. } else {
  272. dashCpuBar.className = 'h-full rounded-full bg-emerald-500 transition-all duration-500';
  273. }
  274. }
  275. const dashCpuCores = document.getElementById('dash-cpu-cores');
  276. if (dashCpuCores) dashCpuCores.innerText = `${s.cpu_cores || 1} Cores`;
  277. const dashCpuLoad = document.getElementById('dash-cpu-load');
  278. if (dashCpuLoad) dashCpuLoad.innerText = loadStr;
  279. const dashCpuStatus = document.getElementById('dash-cpu-status');
  280. if (dashCpuStatus) {
  281. if (cpuPct > 85) {
  282. dashCpuStatus.innerText = 'High';
  283. dashCpuStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  284. } else if (cpuPct > 65) {
  285. dashCpuStatus.innerText = 'Heavy';
  286. dashCpuStatus.className = 'text-[11px] font-semibold text-amber-400 uppercase px-2 py-0.5 rounded bg-amber-500/10';
  287. } else {
  288. dashCpuStatus.innerText = 'Normal';
  289. dashCpuStatus.className = 'text-[11px] font-semibold text-emerald-400 uppercase px-2 py-0.5 rounded bg-emerald-500/10';
  290. }
  291. }
  292. // Compute RAM Metrics
  293. const memPct = Math.round(s.mem_usage_pct || 0);
  294. const memPctStr = `${memPct}%`;
  295. const memWidth = `${Math.max(3, Math.min(100, memPct))}%`;
  296. const usedMB = s.mem_used_mb || 0;
  297. const totalMB = s.mem_total_mb || 0;
  298. const freeMB = totalMB > usedMB ? totalMB - usedMB : 0;
  299. function fmtMemMB(mb) {
  300. if (mb >= 1024) {
  301. return `${(mb / 1024).toFixed(1)} GB`;
  302. }
  303. return `${mb} MB`;
  304. }
  305. // Sidebar RAM
  306. const sideRamVal = document.getElementById('side-ram-val');
  307. if (sideRamVal) sideRamVal.innerText = memPctStr;
  308. const sideRamBar = document.getElementById('side-ram-bar');
  309. if (sideRamBar) sideRamBar.style.width = memWidth;
  310. // Dashboard RAM Card
  311. const dashRamVal = document.getElementById('dash-ram-val');
  312. if (dashRamVal) dashRamVal.innerText = memPctStr;
  313. const dashRamBar = document.getElementById('dash-ram-bar');
  314. if (dashRamBar) {
  315. dashRamBar.style.width = memWidth;
  316. if (memPct > 85) {
  317. dashRamBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  318. } else if (memPct > 70) {
  319. dashRamBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  320. } else {
  321. dashRamBar.className = 'h-full rounded-full bg-indigo-500 transition-all duration-500';
  322. }
  323. }
  324. const dashRamUsedTotal = document.getElementById('dash-ram-used-total');
  325. if (dashRamUsedTotal) {
  326. dashRamUsedTotal.innerText = `${fmtMemMB(usedMB)} / ${fmtMemMB(totalMB)}`;
  327. }
  328. const dashRamFree = document.getElementById('dash-ram-free');
  329. if (dashRamFree) {
  330. dashRamFree.innerText = fmtMemMB(freeMB);
  331. }
  332. const dashRamStatus = document.getElementById('dash-ram-status');
  333. if (dashRamStatus) {
  334. if (memPct > 85) {
  335. dashRamStatus.innerText = 'High';
  336. dashRamStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  337. } else {
  338. dashRamStatus.innerText = 'Active';
  339. dashRamStatus.className = 'text-[11px] font-semibold text-indigo-400 uppercase px-2 py-0.5 rounded bg-indigo-500/10';
  340. }
  341. }
  342. // Legacy Dashboard Stats (Safe checks)
  343. const elIfacesUp = document.getElementById('stat-ifaces-up');
  344. if (elIfacesUp) elIfacesUp.innerText = s.up_ifaces || 0;
  345. const elIfacesTot = document.getElementById('stat-ifaces-total');
  346. if (elIfacesTot) elIfacesTot.innerText = `${s.total_ifaces || 0} Total`;
  347. const elIfacesDown = document.getElementById('stat-ifaces-down');
  348. if (elIfacesDown) elIfacesDown.innerText = `${s.down_ifaces || 0} DOWN`;
  349. const elVlans = document.getElementById('stat-vlans-count');
  350. if (elVlans) elVlans.innerText = s.vlan_ifaces || 0;
  351. // VPN Status Indicators
  352. if (v) {
  353. const totalActive = v.total_active_tunnels || 0;
  354. const statVpnActive = document.getElementById('stat-vpn-active');
  355. if (statVpnActive) statVpnActive.innerText = totalActive;
  356. const tunnelsDot = document.getElementById('tunnels-dot');
  357. const tunnelsLabel = document.getElementById('tunnels-label');
  358. if (tunnelsDot && tunnelsLabel) {
  359. if (totalActive > 0) {
  360. tunnelsDot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  361. tunnelsLabel.innerText = `${totalActive} Active VPN Tunnel${totalActive > 1 ? 's' : ''}`;
  362. } else {
  363. tunnelsDot.className = 'w-2 h-2 rounded-full bg-slate-500';
  364. tunnelsLabel.innerText = '0 Active VPN Tunnels';
  365. }
  366. }
  367. setDotBadge('badge-pppoe-status', (v.active_pppoe || 0) > 0 || v.pppoe_connected);
  368. setDotBadge('badge-wg-status', (v.active_wireguard || 0) > 0 || v.wireguard_active);
  369. setDotBadge('badge-ipsec-status', (v.active_ipsec || 0) > 0 || v.ipsec_active);
  370. setDotBadge('badge-l2tp-status', (v.active_l2tp || 0) > 0 || v.l2tp_connected);
  371. setDotBadge('badge-pptp-status', (v.active_pptp || 0) > 0 || v.pptp_connected);
  372. }
  373. // Total Live Bandwidth Rate
  374. let totalRx = 0;
  375. let totalTx = 0;
  376. (state.interfaces || []).forEach(i => {
  377. if (i.rate) {
  378. totalRx += i.rate.rx_bytes_sec || 0;
  379. totalTx += i.rate.tx_bytes_sec || 0;
  380. }
  381. });
  382. document.getElementById('stat-traffic-rx').innerText = formatTraffic(totalRx);
  383. document.getElementById('stat-traffic-tx').innerText = formatTraffic(totalTx);
  384. }
  385. function setDotBadge(id, active) {
  386. const el = document.getElementById(id);
  387. if (!el) return;
  388. if (active) {
  389. el.className = 'w-2 h-2 rounded-full bg-emerald-400 shadow-sm shadow-emerald-400/80';
  390. } else {
  391. el.className = 'w-2 h-2 rounded-full bg-slate-600';
  392. }
  393. }
  394. function updateBadges() {
  395. const bIfaces = document.getElementById('badge-ifaces-count');
  396. if (bIfaces) bIfaces.innerText = (state.interfaces || []).length;
  397. const bVlans = document.getElementById('badge-vlans-count');
  398. if (bVlans) bVlans.innerText = (state.vlans || []).length;
  399. if (state.fwSummary) {
  400. const totalFwRules = (state.fwSummary.filter_rules_count || 0) + (state.fwSummary.nat_rules_count || 0) + (state.fwSummary.mangle_rules_count || 0);
  401. const badgeFw = document.getElementById('badge-firewall-count');
  402. if (badgeFw) badgeFw.innerText = totalFwRules;
  403. }
  404. if (state.vpnStatus) {
  405. const v = state.vpnStatus;
  406. const bEoIP = document.getElementById('badge-eoip-count');
  407. if (bEoIP) bEoIP.innerText = v.total_eoip || 0;
  408. const bPPPSess = document.getElementById('badge-ppp-sessions');
  409. if (bPPPSess) bPPPSess.innerText = v.total_ppp_sessions || 0;
  410. setDotBadge('badge-pppoe-status', v.active_pppoe > 0 || v.pppoe_server_running);
  411. setDotBadge('badge-wg-status', v.active_wireguard > 0);
  412. setDotBadge('badge-ipsec-status', v.active_ipsec > 0 || v.ipsec_server_running);
  413. setDotBadge('badge-l2tp-status', v.active_l2tp > 0 || v.l2tp_server_running);
  414. setDotBadge('badge-pptp-status', v.active_pptp > 0 || v.pptp_server_running);
  415. }
  416. if (state.dynSummary) {
  417. const d = state.dynSummary;
  418. setDotBadge('badge-bgp-dot', d.bgp_running);
  419. setDotBadge('badge-ospf-dot', d.ospf_running);
  420. const bBgp = document.getElementById('badge-bgp-count');
  421. if (bBgp) bBgp.innerText = (state.bgpPeers || []).length;
  422. const bOspf = document.getElementById('badge-ospf-count');
  423. if (bOspf) bOspf.innerText = (state.ospfInterfaces || []).length;
  424. const bFilters = document.getElementById('badge-filters-count');
  425. if (bFilters) bFilters.innerText = (state.routingFilters || []).length;
  426. }
  427. }
  428. // Render Dashboard View
  429. function renderDashboard() {
  430. const matrix = document.getElementById('port-matrix');
  431. matrix.innerHTML = '';
  432. (state.interfaces || []).forEach(iface => {
  433. const isUp = iface.state === 'UP';
  434. const isVlan = iface.is_vlan;
  435. const portCard = document.createElement('div');
  436. portCard.className = `p-3 rounded-xl border transition-all cursor-pointer select-none group ${
  437. isUp
  438. ? (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')
  439. : 'bg-slate-900/40 border-slate-800/60 opacity-60 hover:opacity-100 hover:border-slate-700'
  440. }`;
  441. portCard.onclick = () => openIfaceModal(iface.name);
  442. let statusPillClass = isUp ? 'bg-emerald-500 shadow-sm shadow-emerald-500/50' : 'bg-rose-500';
  443. if (isVlan) statusPillClass = isUp ? 'bg-cyan-400 shadow-sm shadow-cyan-400/50' : 'bg-rose-500';
  444. portCard.innerHTML = `
  445. <div class="flex items-center justify-between mb-2">
  446. <span class="font-bold text-xs font-mono text-white group-hover:text-brand-400 transition truncate">${iface.name}</span>
  447. <span class="w-2 h-2 rounded-full ${statusPillClass}"></span>
  448. </div>
  449. <div class="text-[11px] font-mono text-slate-300 truncate">${iface.ipv4 && iface.ipv4.length > 0 ? iface.ipv4[0] : (iface.mac || 'No IP')}</div>
  450. <div class="mt-2 flex items-center justify-between text-[10px] text-slate-400">
  451. <span class="uppercase tracking-wider font-semibold">${isVlan ? `VLAN ${iface.vlan_id}` : iface.type}</span>
  452. <span>${iface.rate?.rx_human || '0 B/s'}</span>
  453. </div>
  454. `;
  455. matrix.appendChild(portCard);
  456. });
  457. const ifaceTbody = document.getElementById('quick-interfaces-table');
  458. if (ifaceTbody) {
  459. ifaceTbody.innerHTML = '';
  460. (state.interfaces || []).forEach(i => {
  461. const isUp = i.state === 'UP';
  462. const tr = document.createElement('tr');
  463. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  464. tr.onclick = () => openIfaceModal(i.name);
  465. const rxStr = i.rate?.rx_human || '0 B/s';
  466. const txStr = i.rate?.tx_human || '0 B/s';
  467. tr.innerHTML = `
  468. <td class="py-2.5 font-bold text-white flex items-center gap-2">
  469. <span class="w-2 h-2 rounded-full ${isUp ? 'bg-emerald-400 shadow-sm shadow-emerald-400/50' : 'bg-rose-400'}"></span>
  470. <span>${i.name}</span>
  471. </td>
  472. <td class="py-2.5 text-slate-300 font-sans">
  473. <span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 font-medium">${i.role || i.type || 'Ethernet'}</span>
  474. </td>
  475. <td class="py-2.5 text-slate-400 text-[11px] font-mono">${i.mac || '-'}</td>
  476. <td class="py-2.5 text-slate-200 font-semibold">${i.ipv4 && i.ipv4.length > 0 ? i.ipv4.join(', ') : '<span class="text-slate-600 font-normal">Unassigned</span>'}</td>
  477. <td class="py-2.5 text-slate-300 text-[11px] font-mono">
  478. <span class="text-emerald-400">↓ ${rxStr}</span> <span class="text-slate-600">•</span> <span class="text-cyan-400">↑ ${txStr}</span>
  479. </td>
  480. <td class="py-2.5 text-right font-sans font-semibold">
  481. <span class="px-2 py-0.5 rounded text-[10px] ${isUp ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/20' : 'bg-rose-500/10 text-rose-400 border border-rose-500/20'}">${i.state}</span>
  482. </td>
  483. `;
  484. ifaceTbody.appendChild(tr);
  485. });
  486. }
  487. const vlanTbody = document.getElementById('quick-vlans-table');
  488. if (vlanTbody) {
  489. vlanTbody.innerHTML = '';
  490. }
  491. }
  492. // Expand / Collapse Handlers
  493. function toggleExpand(parentName) {
  494. if (state.expandedParents.has(parentName)) {
  495. state.expandedParents.delete(parentName);
  496. } else {
  497. state.expandedParents.add(parentName);
  498. }
  499. renderInterfacesList();
  500. }
  501. // VLAN Support Checker: 802.1Q sub-interfaces are only supported on physical ethernet, veth, bridge, bond
  502. function supportsVLAN(iface) {
  503. if (!iface) return false;
  504. if (iface.is_vlan) return false;
  505. const name = (iface.name || '').toLowerCase();
  506. const type = (iface.type || '').toLowerCase();
  507. const role = (iface.role || '').toLowerCase();
  508. // Exclude loopback
  509. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  510. // Exclude WireGuard (Layer 3 tunnel, no 802.1Q support)
  511. if (type === 'wireguard' || name.startsWith('wg')) return false;
  512. // Exclude PPP / PPPoE
  513. if (type === 'ppp' || name.startsWith('ppp')) return false;
  514. // Exclude other Layer 3 tunnels and dummy devices
  515. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  516. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  517. return false;
  518. }
  519. // If name already contains a dot, it's already a sub-interface
  520. if (name.includes('.')) return false;
  521. return true;
  522. }
  523. // Expand / Collapse Handlers
  524. function toggleExpand(parentName) {
  525. const childVlans = (state.vlans || []).filter(v => v.parent_name === parentName || v.name.startsWith(parentName + '.'));
  526. if (childVlans.length === 0) {
  527. // Cannot expand an interface with no VLANs
  528. state.expandedParents.delete(parentName);
  529. return;
  530. }
  531. if (state.expandedParents.has(parentName)) {
  532. state.expandedParents.delete(parentName);
  533. } else {
  534. state.expandedParents.add(parentName);
  535. }
  536. renderInterfacesList();
  537. }
  538. function expandAllIfaces(expand) {
  539. if (expand) {
  540. (state.interfaces || []).forEach(i => {
  541. const hasVlans = (state.vlans || []).some(v => v.parent_name === i.name || v.name.startsWith(i.name + '.'));
  542. if (!i.is_vlan && hasVlans) state.expandedParents.add(i.name);
  543. });
  544. } else {
  545. state.expandedParents.clear();
  546. }
  547. renderInterfacesList();
  548. }
  549. // Filter and Render Hierarchical Interfaces List
  550. function filterIfaces(filter) {
  551. state.ifaceFilter = filter || 'all';
  552. renderInterfacesList();
  553. }
  554. function renderInterfacesList() {
  555. const tbody = document.getElementById('interfaces-tree-tbody');
  556. const emptyState = document.getElementById('interfaces-empty-state');
  557. const summary = document.getElementById('ifaces-list-summary');
  558. const query = (document.getElementById('iface-search')?.value || '').trim().toLowerCase();
  559. tbody.innerHTML = '';
  560. const allIfaces = state.interfaces || [];
  561. const allVlans = state.vlans || [];
  562. const parentIfaces = allIfaces.filter(i => !i.is_vlan);
  563. const filteredParents = parentIfaces.filter(parent => {
  564. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  565. if (query) {
  566. const matchName = parent.name.toLowerCase().includes(query);
  567. const matchIp = (parent.ipv4 || []).some(ip => ip.toLowerCase().includes(query));
  568. const matchRole = (parent.role || '').toLowerCase().includes(query);
  569. const matchType = (parent.type || '').toLowerCase().includes(query);
  570. const matchVlan = childVlans.some(v =>
  571. v.name.toLowerCase().includes(query) ||
  572. String(v.vlan_id).includes(query) ||
  573. (v.ipv4 || []).some(ip => ip.toLowerCase().includes(query)) ||
  574. (v.description || '').toLowerCase().includes(query)
  575. );
  576. if (!matchName && !matchIp && !matchRole && !matchType && !matchVlan) return false;
  577. }
  578. if (state.ifaceFilter === 'has_vlans') return childVlans.length > 0;
  579. if (state.ifaceFilter === 'physical') return parent.type !== 'loopback';
  580. if (state.ifaceFilter === 'up') return parent.state === 'UP';
  581. return true;
  582. });
  583. if (summary) {
  584. summary.innerText = `${parentIfaces.length} Interfaces • ${allVlans.length} Active VLANs`;
  585. }
  586. if (filteredParents.length === 0) {
  587. emptyState?.classList.remove('hidden');
  588. return;
  589. }
  590. emptyState?.classList.add('hidden');
  591. filteredParents.forEach(parent => {
  592. const isUp = parent.state === 'UP';
  593. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  594. const hasVlans = childVlans.length > 0;
  595. const isExpanded = hasVlans && state.expandedParents.has(parent.name);
  596. const canHaveVlan = supportsVLAN(parent);
  597. const parentRow = document.createElement('tr');
  598. parentRow.className = `hover:bg-slate-800/50 transition border-b border-slate-800/80 ${isExpanded ? 'bg-slate-900/80' : ''}`;
  599. parentRow.innerHTML = `
  600. <td class="py-3 px-3 text-center">
  601. ${hasVlans ? `
  602. <button onclick="toggleExpand('${parent.name}')" title="${isExpanded ? 'Collapse VLANs' : 'Expand VLANs'}"
  603. class="w-6 h-6 rounded flex items-center justify-center hover:bg-slate-800 text-slate-400 hover:text-white transition">
  604. <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">
  605. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M9 5l7 7-7 7" />
  606. </svg>
  607. </button>
  608. ` : `
  609. <div class="w-6 h-6 flex items-center justify-center text-slate-700 select-none">
  610. <span class="w-1.5 h-1.5 rounded-full bg-slate-800"></span>
  611. </div>
  612. `}
  613. </td>
  614. <td class="py-3 px-4">
  615. <div class="flex items-center space-x-2.5">
  616. <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">
  617. ${parent.type === 'loopback' ? 'LO' : (parent.type === 'wireguard' ? 'WG' : (parent.type === 'bridge' ? 'BR' : 'NIC'))}
  618. </div>
  619. <div>
  620. <div class="flex items-center gap-2">
  621. ${hasVlans ? `
  622. <span class="font-bold text-white text-sm cursor-pointer hover:text-cyan-400" onclick="toggleExpand('${parent.name}')">${parent.name}</span>
  623. <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>
  624. ` : `
  625. <span class="font-bold text-white text-sm">${parent.name}</span>
  626. <span class="text-[10px] bg-slate-800/40 text-slate-500 px-1.5 py-0.5 rounded font-mono select-none">0 VLANs</span>
  627. `}
  628. </div>
  629. <div class="text-[10px] text-slate-500 font-sans mt-0.5">${parent.type}</div>
  630. </div>
  631. </div>
  632. </td>
  633. <td class="py-3 px-4 font-sans">
  634. <div class="flex items-center gap-1.5">
  635. <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>
  636. <span class="text-xs text-slate-400 truncate max-w-[120px]">${parent.description || '-'}</span>
  637. </div>
  638. </td>
  639. <td class="py-3 px-4">
  640. ${parent.ipv4 && parent.ipv4.length > 0
  641. ? `<div class="text-white font-medium">${parent.ipv4[0]}</div>`
  642. : '<span class="text-slate-600 font-sans">Unassigned</span>'
  643. }
  644. ${(() => {
  645. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  646. if (!c) return '';
  647. 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');
  648. 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>`;
  649. })()}
  650. </td>
  651. <td class="py-3 px-4 text-slate-400 text-[11px]">
  652. <div>${parent.mac || 'N/A'}</div>
  653. <div class="text-[10px] text-slate-500">MTU ${parent.mtu}</div>
  654. </td>
  655. <td class="py-3 px-4 text-[11px]">
  656. <div class="flex items-center space-x-2">
  657. <span class="text-emerald-400">↓ ${parent.rate?.rx_human || '0 B/s'}</span>
  658. <span class="text-cyan-400">↑ ${parent.rate?.tx_human || '0 B/s'}</span>
  659. </div>
  660. </td>
  661. <td class="py-3 px-4 font-sans">
  662. <button onclick="toggleInterfaceState('${parent.name}', '${isUp ? 'down' : 'up'}')"
  663. class="flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full transition ${
  664. 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'
  665. }" title="Click to toggle link status">
  666. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  667. <span>${parent.state}</span>
  668. </button>
  669. </td>
  670. <td class="py-3 px-4 text-right space-x-2 font-sans">
  671. ${(() => {
  672. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  673. if (c) {
  674. 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>`;
  675. }
  676. 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>`;
  677. })()}
  678. ${canHaveVlan ? `
  679. <button onclick="openVlanModal('${parent.name}')"
  680. 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">
  681. + Add VLAN
  682. </button>
  683. ` : ''}
  684. <button onclick="openIfaceModal('${parent.name}')"
  685. 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">
  686. Configure
  687. </button>
  688. </td>
  689. `;
  690. tbody.appendChild(parentRow);
  691. if (isExpanded) {
  692. const drawerRow = document.createElement('tr');
  693. drawerRow.className = 'bg-slate-950/80 border-b border-slate-800/90';
  694. const drawerCell = document.createElement('td');
  695. drawerCell.colSpan = 8;
  696. drawerCell.className = 'p-0';
  697. drawerCell.innerHTML = `
  698. <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">
  699. <div class="flex items-center justify-between mb-3">
  700. <div class="flex items-center space-x-3">
  701. <span class="font-bold text-xs text-white uppercase tracking-wider flex items-center gap-1.5 font-sans">
  702. <span>VLAN Sub-interfaces on <code class="text-cyan-300 lowercase">${parent.name}</code></span>
  703. </span>
  704. <span class="text-[11px] bg-cyan-950 text-cyan-400 px-2 py-0.5 rounded-full border border-cyan-800/60 font-mono">
  705. ${childVlans.length} Attached
  706. </span>
  707. </div>
  708. <button onclick="openVlanModal('${parent.name}')"
  709. 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">
  710. <span>+ Create VLAN on ${parent.name}</span>
  711. </button>
  712. </div>
  713. ${childVlans.length === 0 ? `
  714. <div class="p-6 text-center border border-dashed border-slate-800 rounded-xl bg-slate-900/40 font-sans">
  715. <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>
  716. <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">
  717. <span>+ Create Your First VLAN on ${parent.name}</span>
  718. </button>
  719. </div>
  720. ` : `
  721. <div class="overflow-x-auto rounded-lg border border-slate-800 bg-slate-900/90 shadow-inner">
  722. <table class="w-full text-left text-xs font-mono">
  723. <thead class="text-slate-400 bg-slate-950/70 border-b border-slate-800 uppercase tracking-wider text-[10px] font-sans">
  724. <tr>
  725. <th class="py-2.5 px-4">VLAN ID</th>
  726. <th class="py-2.5 px-4">Interface Device</th>
  727. <th class="py-2.5 px-4">Subnet Gateway</th>
  728. <th class="py-2.5 px-4">Role / Alias</th>
  729. <th class="py-2.5 px-4">MTU</th>
  730. <th class="py-2.5 px-4">Throughput</th>
  731. <th class="py-2.5 px-4">Status</th>
  732. <th class="py-2.5 px-4 text-right">Actions</th>
  733. </tr>
  734. </thead>
  735. <tbody class="divide-y divide-slate-800/70">
  736. ${childVlans.map(v => {
  737. const isVlanUp = v.state === 'UP';
  738. return `
  739. <tr class="hover:bg-slate-800/40 transition">
  740. <td class="py-2.5 px-4">
  741. <span class="px-2 py-0.5 rounded text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800 shadow-sm">
  742. VLAN ${v.vlan_id}
  743. </span>
  744. </td>
  745. <td class="py-2.5 px-4 font-bold text-white flex items-center gap-1.5">
  746. <span class="text-cyan-500">└─</span>
  747. <span>${v.name}</span>
  748. </td>
  749. <td class="py-2.5 px-4 text-emerald-400 font-medium">
  750. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  751. ${(() => {
  752. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  753. if (!c) return '';
  754. 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';
  755. 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>`;
  756. })()}
  757. </td>
  758. <td class="py-2.5 px-4 font-sans text-slate-300">
  759. <span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 mr-1.5">${v.role || 'VLAN'}</span>
  760. <span class="text-slate-400 text-xs">${v.description || '-'}</span>
  761. </td>
  762. <td class="py-2.5 px-4 text-slate-400">${v.mtu}</td>
  763. <td class="py-2.5 px-4 text-[11px]">
  764. <span class="text-emerald-400">↓ ${v.rate?.rx_human || '0 B/s'}</span>
  765. <span class="text-cyan-400 ml-1.5">↑ ${v.rate?.tx_human || '0 B/s'}</span>
  766. </td>
  767. <td class="py-2.5 px-4 font-sans">
  768. <button onclick="toggleInterfaceState('${v.name}', '${isVlanUp ? 'down' : 'up'}')"
  769. class="flex items-center gap-1 text-[11px] font-semibold px-2 py-0.5 rounded-full ${
  770. 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'
  771. }">
  772. <span class="w-1.5 h-1.5 rounded-full ${isVlanUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  773. <span>${v.state}</span>
  774. </button>
  775. </td>
  776. <td class="py-2.5 px-4 text-right space-x-1.5 font-sans">
  777. ${(() => {
  778. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  779. if (c) {
  780. 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>`;
  781. }
  782. 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>`;
  783. })()}
  784. <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>
  785. <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>
  786. </td>
  787. </tr>
  788. `;
  789. }).join('')}
  790. </tbody>
  791. </table>
  792. </div>
  793. `}
  794. </div>
  795. `;
  796. drawerRow.appendChild(drawerCell);
  797. tbody.appendChild(drawerRow);
  798. }
  799. });
  800. }
  801. // Render VLANs Dedicated View
  802. function renderVlansList() {
  803. const tbody = document.getElementById('vlans-table-body');
  804. if (!tbody) return;
  805. const emptyState = document.getElementById('vlans-empty-state');
  806. const countBadge = document.getElementById('vlans-table-count');
  807. const query = (document.getElementById('vlan-search')?.value || '').toLowerCase();
  808. tbody.innerHTML = '';
  809. const allVlans = state.vlans || [];
  810. if (countBadge) countBadge.innerText = allVlans.length;
  811. const filtered = allVlans.filter(v => {
  812. if (!query) return true;
  813. return v.name.toLowerCase().includes(query) ||
  814. String(v.vlan_id).includes(query) ||
  815. (v.description || '').toLowerCase().includes(query) ||
  816. (v.ipv4 && v.ipv4.some(ip => ip.includes(query)));
  817. });
  818. if (allVlans.length === 0) {
  819. emptyState.classList.remove('hidden');
  820. return;
  821. }
  822. emptyState.classList.add('hidden');
  823. filtered.forEach(v => {
  824. const isUp = v.state === 'UP';
  825. const tr = document.createElement('tr');
  826. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  827. tr.innerHTML = `
  828. <td class="py-3 px-4">
  829. <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">
  830. VLAN ${v.vlan_id}
  831. </span>
  832. </td>
  833. <td class="py-3 px-4 font-bold text-white">${v.name}</td>
  834. <td class="py-3 px-4 text-slate-300">
  835. <span class="bg-slate-800 text-slate-200 px-2 py-0.5 rounded text-[11px]">${v.parent_name || 'eth0'}</span>
  836. </td>
  837. <td class="py-3 px-4 text-emerald-400 font-medium">
  838. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  839. </td>
  840. <td class="py-3 px-4 text-slate-300 font-sans">
  841. <span class="text-slate-400 text-xs">${v.description || v.role || '-'}</span>
  842. </td>
  843. <td class="py-3 px-4 text-slate-400">${v.mtu}</td>
  844. <td class="py-3 px-4 font-sans">
  845. <button onclick="toggleInterfaceState('${v.name}', '${isUp ? 'down' : 'up'}')"
  846. class="flex items-center gap-1.5 text-xs font-semibold px-2 py-0.5 rounded-full ${
  847. 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'
  848. }">
  849. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  850. <span>${v.state}</span>
  851. </button>
  852. </td>
  853. <td class="py-3 px-4 text-right space-x-2 font-sans">
  854. <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>
  855. <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>
  856. </td>
  857. `;
  858. tbody.appendChild(tr);
  859. });
  860. }
  861. // Toggle interface UP / DOWN
  862. async function toggleInterfaceState(name, newState) {
  863. try {
  864. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(name)}/state`, {
  865. method: 'POST',
  866. headers: { 'Content-Type': 'application/json' },
  867. body: JSON.stringify({ state: newState })
  868. });
  869. const data = await res.json();
  870. if (res.ok) {
  871. showToast('Interface Updated', `Interface ${name} is now ${newState.toUpperCase()}`, 'success');
  872. fetchData(false);
  873. } else {
  874. showToast('Error', data.message || 'Failed to toggle interface state', 'error');
  875. }
  876. } catch (err) {
  877. showToast('Error', err.message, 'error');
  878. }
  879. }
  880. // ---------------- MikroTik Flag & Utilities ----------------
  881. function renderMikroTikFlag(running, disabled) {
  882. if (running) {
  883. 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>`;
  884. }
  885. if (disabled) {
  886. 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>`;
  887. }
  888. 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>`;
  889. }
  890. function copyToClipboard(text, label = 'Text') {
  891. navigator.clipboard.writeText(text).then(() => {
  892. showToast('Copied', `${label} copied to clipboard`, 'success');
  893. }).catch(() => {
  894. prompt('Copy value:', text);
  895. });
  896. }
  897. // ======================== PPPoE Multi-Instance ========================
  898. async function loadPPPoE(populateInputs = true) {
  899. try {
  900. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`);
  901. const list = await res.json();
  902. state.pppoeList = Array.isArray(list) ? list : [];
  903. const badge = document.getElementById('pppoe-count-badge');
  904. if (badge) badge.innerText = `${state.pppoeList.length} Interface${state.pppoeList.length !== 1 ? 's' : ''}`;
  905. const tbody = document.getElementById('pppoe-table-body');
  906. const empty = document.getElementById('pppoe-empty');
  907. if (!tbody) return;
  908. tbody.innerHTML = '';
  909. if (state.pppoeList.length === 0) {
  910. if (empty) empty.classList.remove('hidden');
  911. } else {
  912. if (empty) empty.classList.add('hidden');
  913. state.pppoeList.forEach(inst => {
  914. const tr = document.createElement('tr');
  915. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  916. tr.innerHTML = `
  917. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  918. <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
  919. <td class="py-2.5 px-3 text-cyan-400 font-mono">${inst.interface}</td>
  920. <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
  921. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
  922. <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
  923. <td class="py-2.5 px-3 text-center">
  924. <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'}">
  925. ${inst.default_route ? 'Yes' : 'No'}
  926. </span>
  927. </td>
  928. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  929. ${inst.running ? `
  930. <button onclick="disconnectPPPoEInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  931. ` : `
  932. <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>
  933. `}
  934. <button onclick="togglePPPoEState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  935. ${inst.disabled ? 'Enable' : 'Disable'}
  936. </button>
  937. <button onclick="openEditPPPoEModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  938. <button onclick="deletePPPoEInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  939. </td>
  940. `;
  941. tbody.appendChild(tr);
  942. });
  943. }
  944. } catch (err) {
  945. console.error('Failed to load PPPoE:', err);
  946. }
  947. }
  948. function openAddPPPoEModal() {
  949. document.getElementById('pppoe-modal-title').innerText = 'Add PPPoE Client Interface';
  950. document.getElementById('pppoe-modal-edit-orig').value = '';
  951. document.getElementById('pppoe-modal-name').value = `pppoe-out${(state.pppoeList || []).length + 1}`;
  952. document.getElementById('pppoe-modal-name').readOnly = false;
  953. document.getElementById('pppoe-modal-user').value = '';
  954. document.getElementById('pppoe-modal-pass').value = '';
  955. document.getElementById('pppoe-modal-service').value = '';
  956. document.getElementById('pppoe-modal-mtu').value = '1492';
  957. document.getElementById('pppoe-modal-defroute').checked = true;
  958. document.getElementById('pppoe-modal-reconnect').checked = true;
  959. document.getElementById('pppoe-modal-disabled').checked = false;
  960. // Populate interfaces
  961. const sel = document.getElementById('pppoe-modal-iface');
  962. sel.innerHTML = '';
  963. (state.interfaces || []).forEach(i => {
  964. if (i.name === 'lo') return;
  965. const opt = document.createElement('option');
  966. opt.value = i.name;
  967. opt.innerText = `${i.name} (${i.role || i.type})`;
  968. sel.appendChild(opt);
  969. });
  970. document.getElementById('pppoe-modal').classList.remove('hidden');
  971. }
  972. function openEditPPPoEModal(name) {
  973. const inst = (state.pppoeList || []).find(i => i.name === name);
  974. if (!inst) return;
  975. document.getElementById('pppoe-modal-title').innerText = `Edit PPPoE Client: ${name}`;
  976. document.getElementById('pppoe-modal-edit-orig').value = name;
  977. document.getElementById('pppoe-modal-name').value = inst.name;
  978. document.getElementById('pppoe-modal-name').readOnly = true;
  979. document.getElementById('pppoe-modal-user').value = inst.username || '';
  980. document.getElementById('pppoe-modal-pass').value = inst.password || '';
  981. document.getElementById('pppoe-modal-service').value = inst.service_name || '';
  982. document.getElementById('pppoe-modal-mtu').value = inst.mtu || 1492;
  983. document.getElementById('pppoe-modal-defroute').checked = inst.default_route ?? true;
  984. document.getElementById('pppoe-modal-reconnect').checked = inst.auto_reconnect ?? true;
  985. document.getElementById('pppoe-modal-disabled').checked = !!inst.disabled;
  986. const sel = document.getElementById('pppoe-modal-iface');
  987. sel.innerHTML = '';
  988. (state.interfaces || []).forEach(i => {
  989. if (i.name === 'lo') return;
  990. const opt = document.createElement('option');
  991. opt.value = i.name;
  992. opt.innerText = `${i.name} (${i.role || i.type})`;
  993. if (i.name === inst.interface) opt.selected = true;
  994. sel.appendChild(opt);
  995. });
  996. document.getElementById('pppoe-modal').classList.remove('hidden');
  997. }
  998. function closePPPoEModal() {
  999. document.getElementById('pppoe-modal').classList.add('hidden');
  1000. }
  1001. async function submitSavePPPoE(e) {
  1002. e.preventDefault();
  1003. const name = document.getElementById('pppoe-modal-name').value.trim();
  1004. const iface = document.getElementById('pppoe-modal-iface').value;
  1005. const user = document.getElementById('pppoe-modal-user').value.trim();
  1006. const pass = document.getElementById('pppoe-modal-pass').value;
  1007. const service = document.getElementById('pppoe-modal-service').value.trim();
  1008. const mtu = parseInt(document.getElementById('pppoe-modal-mtu').value, 10) || 1492;
  1009. const defRoute = document.getElementById('pppoe-modal-defroute').checked;
  1010. const reconnect = document.getElementById('pppoe-modal-reconnect').checked;
  1011. const disabled = document.getElementById('pppoe-modal-disabled').checked;
  1012. try {
  1013. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`, {
  1014. method: 'POST',
  1015. headers: { 'Content-Type': 'application/json' },
  1016. body: JSON.stringify({
  1017. name,
  1018. interface: iface,
  1019. username: user,
  1020. password: pass,
  1021. service_name: service,
  1022. mtu,
  1023. default_route: defRoute,
  1024. auto_reconnect: reconnect,
  1025. disabled
  1026. })
  1027. });
  1028. if (res.ok) {
  1029. showToast('PPPoE Saved', `Configuration for ${name} saved`, 'success');
  1030. closePPPoEModal();
  1031. loadPPPoE(false);
  1032. fetchData(false);
  1033. } else {
  1034. const err = await res.json();
  1035. showToast('Error', err.message || 'Failed to save PPPoE', 'error');
  1036. }
  1037. } catch (err) {
  1038. showToast('Error', err.message, 'error');
  1039. }
  1040. }
  1041. async function connectPPPoEInstance(name) {
  1042. try {
  1043. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1044. if (res.ok) {
  1045. showToast('Connecting', `Dialing ${name}...`, 'info');
  1046. setTimeout(() => loadPPPoE(false), 2000);
  1047. }
  1048. } catch (err) {
  1049. showToast('Error', err.message, 'error');
  1050. }
  1051. }
  1052. async function disconnectPPPoEInstance(name) {
  1053. try {
  1054. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1055. if (res.ok) {
  1056. showToast('Disconnected', `${name} session terminated`, 'info');
  1057. setTimeout(() => loadPPPoE(false), 1000);
  1058. }
  1059. } catch (err) {
  1060. showToast('Error', err.message, 'error');
  1061. }
  1062. }
  1063. async function togglePPPoEState(name, enable) {
  1064. try {
  1065. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/state`, {
  1066. method: 'POST',
  1067. headers: { 'Content-Type': 'application/json' },
  1068. body: JSON.stringify({ enabled: enable })
  1069. });
  1070. if (res.ok) {
  1071. showToast(enable ? 'Enabled' : 'Disabled', `${name} is now ${enable ? 'enabled' : 'disabled'}`, 'info');
  1072. loadPPPoE(false);
  1073. }
  1074. } catch (err) {
  1075. showToast('Error', err.message, 'error');
  1076. }
  1077. }
  1078. async function deletePPPoEInstance(name) {
  1079. if (!confirm(`Are you sure you want to delete PPPoE client ${name}?`)) return;
  1080. try {
  1081. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1082. if (res.ok) {
  1083. showToast('Deleted', `PPPoE client ${name} removed`, 'success');
  1084. loadPPPoE(false);
  1085. fetchData(false);
  1086. }
  1087. } catch (err) {
  1088. showToast('Error', err.message, 'error');
  1089. }
  1090. }
  1091. // ======================== WireGuard Multi-Interface & Multi-Peer ========================
  1092. state.wgSubTab = 'ifaces';
  1093. function switchWGSubTab(tab) {
  1094. state.wgSubTab = tab;
  1095. const ifacesPanel = document.getElementById('wg-subtab-ifaces');
  1096. const peersPanel = document.getElementById('wg-subtab-peers');
  1097. const ifacesBtn = document.getElementById('wg-subtab-btn-ifaces');
  1098. const peersBtn = document.getElementById('wg-subtab-btn-peers');
  1099. if (tab === 'ifaces') {
  1100. ifacesPanel?.classList.remove('hidden');
  1101. peersPanel?.classList.add('hidden');
  1102. 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';
  1103. 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';
  1104. } else {
  1105. ifacesPanel?.classList.add('hidden');
  1106. peersPanel?.classList.remove('hidden');
  1107. 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';
  1108. 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';
  1109. renderWGPeers();
  1110. }
  1111. }
  1112. async function loadWireGuard(populateInputs = true) {
  1113. try {
  1114. const [ifacesRes, peersRes] = await Promise.all([
  1115. fetch(`${API_BASE}/vpn/wireguard/interfaces`),
  1116. fetch(`${API_BASE}/vpn/wireguard/peers`)
  1117. ]);
  1118. const ifaces = ifacesRes.ok ? await ifacesRes.json() : [];
  1119. const peers = peersRes.ok ? await peersRes.json() : [];
  1120. state.wgInterfaces = Array.isArray(ifaces) ? ifaces : [];
  1121. state.wgPeers = Array.isArray(peers) ? peers : [];
  1122. // Badges
  1123. const ifacesCountBadge = document.getElementById('wg-ifaces-count');
  1124. if (ifacesCountBadge) ifacesCountBadge.innerText = `${state.wgInterfaces.length} Interfaces`;
  1125. const peersCountBadge = document.getElementById('wg-peers-count');
  1126. if (peersCountBadge) peersCountBadge.innerText = `${state.wgPeers.length} Peers`;
  1127. const subTabIfaces = document.getElementById('wg-subtab-badge-ifaces');
  1128. if (subTabIfaces) subTabIfaces.innerText = state.wgInterfaces.length;
  1129. const subTabPeers = document.getElementById('wg-subtab-badge-peers');
  1130. if (subTabPeers) subTabPeers.innerText = state.wgPeers.length;
  1131. // Render Interfaces
  1132. const ifacesTbody = document.getElementById('wg-ifaces-table-body');
  1133. const ifacesEmpty = document.getElementById('wg-ifaces-empty');
  1134. if (ifacesTbody) {
  1135. ifacesTbody.innerHTML = '';
  1136. if (state.wgInterfaces.length === 0) {
  1137. if (ifacesEmpty) ifacesEmpty.classList.remove('hidden');
  1138. } else {
  1139. if (ifacesEmpty) ifacesEmpty.classList.add('hidden');
  1140. state.wgInterfaces.forEach(iface => {
  1141. const peersOnIface = state.wgPeers.filter(p => p.interface === iface.name).length;
  1142. const tr = document.createElement('tr');
  1143. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1144. tr.innerHTML = `
  1145. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(iface.running, iface.disabled)}</td>
  1146. <td class="py-2.5 px-3">
  1147. <div class="flex items-center gap-1.5">
  1148. <span class="font-bold text-white">${escapeHtml(iface.name)}</span>
  1149. ${iface.comment ? `<span class="text-[10px] text-slate-400 font-sans italic">(${escapeHtml(iface.comment)})</span>` : ''}
  1150. </div>
  1151. </td>
  1152. <td class="py-2.5 px-3 text-amber-400 font-mono">${iface.listen_port}</td>
  1153. <td class="py-2.5 px-3 text-emerald-400 font-mono">${iface.address || '<span class="text-slate-600 font-sans">--</span>'}</td>
  1154. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1155. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${iface.public_key}', 'Public Key')" title="Click to copy: ${iface.public_key}">
  1156. ${(iface.public_key || '').substring(0, 10)}... 📋
  1157. </span>
  1158. </td>
  1159. <td class="py-2.5 px-3 text-slate-400 font-mono">${iface.mtu || 1420}</td>
  1160. <td class="py-2.5 px-3 text-center">
  1161. <span class="px-2 py-0.5 rounded text-[10px] font-sans bg-slate-800 text-slate-300">${peersOnIface} peer${peersOnIface !== 1 ? 's' : ''}</span>
  1162. </td>
  1163. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  1164. ${iface.running ? `
  1165. <button onclick="stopWGInterface('${iface.name}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Stop</button>
  1166. ` : `
  1167. <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>
  1168. `}
  1169. <button onclick="toggleWGInterfaceState('${iface.name}', ${iface.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white font-medium">
  1170. ${iface.disabled ? 'Enable' : 'Disable'}
  1171. </button>
  1172. <button onclick="openEditWGInterfaceModal('${iface.name}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1173. <button onclick="deleteWGInterface('${iface.name}')" class="text-xs text-slate-500 hover:text-rose-400 font-medium">Delete</button>
  1174. </td>
  1175. `;
  1176. ifacesTbody.appendChild(tr);
  1177. });
  1178. }
  1179. }
  1180. // Populate filter dropdown in peers tab
  1181. const filterSel = document.getElementById('wg-peers-filter-iface');
  1182. if (filterSel) {
  1183. const currentVal = filterSel.value;
  1184. filterSel.innerHTML = '<option value="">All Interfaces</option>';
  1185. state.wgInterfaces.forEach(i => {
  1186. const opt = document.createElement('option');
  1187. opt.value = i.name;
  1188. opt.innerText = i.name;
  1189. if (i.name === currentVal) opt.selected = true;
  1190. filterSel.appendChild(opt);
  1191. });
  1192. }
  1193. renderWGPeers();
  1194. } catch (err) {
  1195. console.error('Failed to load WireGuard:', err);
  1196. }
  1197. }
  1198. function renderWGPeers() {
  1199. const filterSel = document.getElementById('wg-peers-filter-iface');
  1200. const selectedIface = filterSel ? filterSel.value : '';
  1201. const tbody = document.getElementById('wg-peers-table-body');
  1202. const empty = document.getElementById('wg-peers-empty');
  1203. if (!tbody) return;
  1204. tbody.innerHTML = '';
  1205. const filtered = selectedIface ? state.wgPeers.filter(p => p.interface === selectedIface) : state.wgPeers;
  1206. if (filtered.length === 0) {
  1207. if (empty) empty.classList.remove('hidden');
  1208. } else {
  1209. if (empty) empty.classList.add('hidden');
  1210. filtered.forEach(p => {
  1211. const isOnline = p.latest_handshake && !p.latest_handshake.includes('Never');
  1212. const tr = document.createElement('tr');
  1213. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1214. tr.innerHTML = `
  1215. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isOnline, p.disabled)}</td>
  1216. <td class="py-2.5 px-3 font-mono font-bold text-rose-400">${escapeHtml(p.interface)}</td>
  1217. <td class="py-2.5 px-3 font-bold text-white font-sans">${escapeHtml(p.name || 'Unnamed')}</td>
  1218. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1219. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${p.public_key}', 'Peer Public Key')" title="${p.public_key}">
  1220. ${(p.public_key || '').substring(0, 10)}... 📋
  1221. </span>
  1222. </td>
  1223. <td class="py-2.5 px-3 text-emerald-400 font-mono font-semibold">${(p.allowed_ips || []).join(', ')}</td>
  1224. <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>
  1225. <td class="py-2.5 px-3 text-slate-300 font-sans">${p.latest_handshake || 'Never'}</td>
  1226. <td class="py-2.5 px-3 font-mono text-[11px]">
  1227. <span class="text-emerald-400">↓ ${p.transfer_rx_human || '0 B'}</span>
  1228. <span class="text-cyan-400 ml-1">↑ ${p.transfer_tx_human || '0 B'}</span>
  1229. </td>
  1230. <td class="py-2.5 px-3 text-right font-sans space-x-2 whitespace-nowrap">
  1231. <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">
  1232. ${p.disabled ? 'Enable' : 'Disable'}
  1233. </button>
  1234. <button onclick="openEditWGPeerModal('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1235. <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>
  1236. <button onclick="deleteWGPeer('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Delete</button>
  1237. </td>
  1238. `;
  1239. tbody.appendChild(tr);
  1240. });
  1241. }
  1242. }
  1243. function openAddWGInterfaceModal() {
  1244. document.getElementById('wg-iface-modal-title').innerText = 'Add WireGuard Interface';
  1245. document.getElementById('wg-iface-modal-edit-orig').value = '';
  1246. const nameEl = document.getElementById('wg-iface-modal-name');
  1247. nameEl.value = `wg${(state.wgInterfaces || []).length}`;
  1248. nameEl.readOnly = false;
  1249. document.getElementById('wg-iface-modal-port').value = 51820 + (state.wgInterfaces || []).length;
  1250. document.getElementById('wg-iface-modal-addr').value = `10.${10 + (state.wgInterfaces || []).length}.0.1/24`;
  1251. document.getElementById('wg-iface-modal-mtu').value = '1420';
  1252. document.getElementById('wg-iface-modal-comment').value = '';
  1253. document.getElementById('wg-iface-modal-pubkey').value = '';
  1254. document.getElementById('wg-iface-modal-privkey').value = '';
  1255. document.getElementById('wg-iface-modal-disabled').checked = false;
  1256. generateWGInterfaceKeys();
  1257. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1258. }
  1259. function openEditWGInterfaceModal(name) {
  1260. const iface = (state.wgInterfaces || []).find(i => i.name === name);
  1261. if (!iface) return;
  1262. document.getElementById('wg-iface-modal-title').innerText = `Edit WireGuard Interface: ${name}`;
  1263. document.getElementById('wg-iface-modal-edit-orig').value = name;
  1264. const nameEl = document.getElementById('wg-iface-modal-name');
  1265. nameEl.value = iface.name;
  1266. nameEl.readOnly = false; // ALLOW RENAMING
  1267. document.getElementById('wg-iface-modal-port').value = iface.listen_port || 51820;
  1268. document.getElementById('wg-iface-modal-addr').value = iface.address || '';
  1269. document.getElementById('wg-iface-modal-mtu').value = iface.mtu || 1420;
  1270. document.getElementById('wg-iface-modal-comment').value = iface.comment || '';
  1271. document.getElementById('wg-iface-modal-pubkey').value = iface.public_key || '';
  1272. document.getElementById('wg-iface-modal-privkey').value = iface.private_key || '';
  1273. document.getElementById('wg-iface-modal-disabled').checked = !!iface.disabled;
  1274. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1275. }
  1276. function closeAddWGInterfaceModal() {
  1277. document.getElementById('wg-iface-modal').classList.add('hidden');
  1278. }
  1279. async function generateWGInterfaceKeys() {
  1280. try {
  1281. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1282. const keys = await res.json();
  1283. if (res.ok) {
  1284. document.getElementById('wg-iface-modal-privkey').value = keys.private_key;
  1285. document.getElementById('wg-iface-modal-pubkey').value = keys.public_key;
  1286. }
  1287. } catch (err) {
  1288. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1289. }
  1290. }
  1291. async function onWGInterfacePrivKeyInput() {
  1292. const privKey = document.getElementById('wg-iface-modal-privkey').value.trim();
  1293. if (!privKey) return;
  1294. try {
  1295. const res = await fetch(`${API_BASE}/vpn/wireguard/calc-pubkey`, {
  1296. method: 'POST',
  1297. headers: { 'Content-Type': 'application/json' },
  1298. body: JSON.stringify({ private_key: privKey })
  1299. });
  1300. if (res.ok) {
  1301. const data = await res.json();
  1302. if (data.public_key) {
  1303. document.getElementById('wg-iface-modal-pubkey').value = data.public_key;
  1304. }
  1305. }
  1306. } catch (err) {
  1307. // Ignore while typing
  1308. }
  1309. }
  1310. function toggleWGPrivKeyVisibility() {
  1311. const el = document.getElementById('wg-iface-modal-privkey');
  1312. const btn = document.getElementById('btn-toggle-wg-privkey');
  1313. if (el.type === 'password') {
  1314. el.type = 'text';
  1315. btn.innerText = '🙈 Hide';
  1316. } else {
  1317. el.type = 'password';
  1318. btn.innerText = '👁️ Show';
  1319. }
  1320. }
  1321. function copyWGInterfacePubKey() {
  1322. const pub = document.getElementById('wg-iface-modal-pubkey').value;
  1323. if (pub) copyToClipboard(pub, 'Interface Public Key');
  1324. }
  1325. async function submitSaveWGInterface(e) {
  1326. e.preventDefault();
  1327. const origName = document.getElementById('wg-iface-modal-edit-orig').value.trim();
  1328. const name = document.getElementById('wg-iface-modal-name').value.trim();
  1329. const port = parseInt(document.getElementById('wg-iface-modal-port').value, 10) || 51820;
  1330. const addr = document.getElementById('wg-iface-modal-addr').value.trim();
  1331. const mtu = parseInt(document.getElementById('wg-iface-modal-mtu').value, 10) || 1420;
  1332. const comment = document.getElementById('wg-iface-modal-comment').value.trim();
  1333. const pub = document.getElementById('wg-iface-modal-pubkey').value.trim();
  1334. const priv = document.getElementById('wg-iface-modal-privkey').value.trim();
  1335. const disabled = document.getElementById('wg-iface-modal-disabled').checked;
  1336. try {
  1337. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces`, {
  1338. method: 'POST',
  1339. headers: { 'Content-Type': 'application/json' },
  1340. body: JSON.stringify({
  1341. orig_name: origName,
  1342. name,
  1343. listen_port: port,
  1344. address: addr,
  1345. mtu,
  1346. comment,
  1347. public_key: pub,
  1348. private_key: priv,
  1349. disabled
  1350. })
  1351. });
  1352. const data = await res.json();
  1353. if (res.ok) {
  1354. showToast('WireGuard Saved', `Interface ${name} configured successfully`, 'success');
  1355. closeAddWGInterfaceModal();
  1356. loadWireGuard(false);
  1357. fetchData(false);
  1358. } else {
  1359. showToast('Error', data.error || 'Failed to save interface', 'error');
  1360. }
  1361. } catch (err) {
  1362. showToast('Error', err.message, 'error');
  1363. }
  1364. }
  1365. async function startWGInterface(name) {
  1366. try {
  1367. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1368. if (res.ok) {
  1369. showToast('Interface UP', `Started WireGuard interface ${name}`, 'success');
  1370. loadWireGuard(false);
  1371. fetchData(false);
  1372. }
  1373. } catch (err) {
  1374. showToast('Error', err.message, 'error');
  1375. }
  1376. }
  1377. async function stopWGInterface(name) {
  1378. try {
  1379. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1380. if (res.ok) {
  1381. showToast('Interface DOWN', `Stopped WireGuard interface ${name}`, 'info');
  1382. loadWireGuard(false);
  1383. fetchData(false);
  1384. }
  1385. } catch (err) {
  1386. showToast('Error', err.message, 'error');
  1387. }
  1388. }
  1389. async function toggleWGInterfaceState(name, enable) {
  1390. try {
  1391. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/state`, {
  1392. method: 'POST',
  1393. headers: { 'Content-Type': 'application/json' },
  1394. body: JSON.stringify({ enabled: enable })
  1395. });
  1396. if (res.ok) {
  1397. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1398. loadWireGuard(false);
  1399. fetchData(false);
  1400. }
  1401. } catch (err) {
  1402. showToast('Error', err.message, 'error');
  1403. }
  1404. }
  1405. async function deleteWGInterface(name) {
  1406. if (!confirm(`Are you sure you want to delete WireGuard interface ${name}? All associated peers will also be removed.`)) return;
  1407. try {
  1408. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1409. if (res.ok) {
  1410. showToast('Deleted', `Interface ${name} removed`, 'success');
  1411. loadWireGuard(false);
  1412. fetchData(false);
  1413. }
  1414. } catch (err) {
  1415. showToast('Error', err.message, 'error');
  1416. }
  1417. }
  1418. function populateWGPeerIfaceSelect(selectedIface = '') {
  1419. const sel = document.getElementById('wg-peer-modal-iface');
  1420. if (!sel) return;
  1421. sel.innerHTML = '';
  1422. (state.wgInterfaces || []).forEach(i => {
  1423. const opt = document.createElement('option');
  1424. opt.value = i.name;
  1425. opt.innerText = `${i.name} (${i.address || 'No IP'})`;
  1426. if (i.name === selectedIface) opt.selected = true;
  1427. sel.appendChild(opt);
  1428. });
  1429. }
  1430. function openAddWGPeerModal() {
  1431. if ((state.wgInterfaces || []).length === 0) {
  1432. showToast('No Interfaces', 'Please add a WireGuard interface first before adding peers', 'warning');
  1433. openAddWGInterfaceModal();
  1434. return;
  1435. }
  1436. document.getElementById('wg-peer-modal-title').innerText = 'Add WireGuard Peer';
  1437. document.getElementById('wg-peer-modal-edit-orig-iface').value = '';
  1438. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = '';
  1439. populateWGPeerIfaceSelect();
  1440. document.getElementById('wg-peer-modal-name').value = '';
  1441. document.getElementById('wg-peer-modal-pubkey').value = '';
  1442. document.getElementById('wg-peer-modal-allowedips').value = '10.10.0.2/32';
  1443. document.getElementById('wg-peer-modal-endpoint').value = '';
  1444. document.getElementById('wg-peer-modal-port').value = '';
  1445. document.getElementById('wg-peer-modal-keepalive').value = '25';
  1446. document.getElementById('wg-peer-modal-preshared').value = '';
  1447. document.getElementById('wg-peer-modal-disabled').checked = false;
  1448. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  1449. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  1450. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1451. }
  1452. function openEditWGPeerModal(ifaceName, pubKey) {
  1453. const peer = (state.wgPeers || []).find(p => p.interface === ifaceName && p.public_key === pubKey);
  1454. if (!peer) {
  1455. showToast('Not Found', 'Peer not found', 'warning');
  1456. return;
  1457. }
  1458. document.getElementById('wg-peer-modal-title').innerText = `Edit WireGuard Peer (${peer.name || ifaceName})`;
  1459. document.getElementById('wg-peer-modal-edit-orig-iface').value = peer.interface;
  1460. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = peer.public_key;
  1461. populateWGPeerIfaceSelect(peer.interface);
  1462. document.getElementById('wg-peer-modal-name').value = peer.name || '';
  1463. document.getElementById('wg-peer-modal-pubkey').value = peer.public_key || '';
  1464. document.getElementById('wg-peer-modal-allowedips').value = (peer.allowed_ips || []).join(', ');
  1465. document.getElementById('wg-peer-modal-endpoint').value = peer.endpoint_address || '';
  1466. document.getElementById('wg-peer-modal-port').value = peer.endpoint_port || '';
  1467. document.getElementById('wg-peer-modal-keepalive').value = peer.persistent_keepalive ?? 25;
  1468. document.getElementById('wg-peer-modal-preshared').value = peer.preshared_key || '';
  1469. document.getElementById('wg-peer-modal-disabled').checked = !!peer.disabled;
  1470. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  1471. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  1472. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1473. }
  1474. function closeAddWGPeerModal() {
  1475. document.getElementById('wg-peer-modal').classList.add('hidden');
  1476. }
  1477. async function generatePeerKeypairHelper() {
  1478. try {
  1479. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1480. const keys = await res.json();
  1481. if (res.ok) {
  1482. document.getElementById('wg-peer-modal-pubkey').value = keys.public_key;
  1483. document.getElementById('wg-peer-gen-privkey').value = keys.private_key;
  1484. document.getElementById('wg-peer-gen-key-box').classList.remove('hidden');
  1485. checkWGPeerKeyValidity();
  1486. showToast('Keypair Generated', 'Public key inserted and client private key ready to copy', 'info');
  1487. }
  1488. } catch (err) {
  1489. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1490. }
  1491. }
  1492. function copyGeneratedPeerPrivKey() {
  1493. const priv = document.getElementById('wg-peer-gen-privkey').value;
  1494. if (priv) copyToClipboard(priv, 'Client Private Key');
  1495. }
  1496. async function generatePeerPSK() {
  1497. try {
  1498. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1499. const keys = await res.json();
  1500. if (res.ok && keys.private_key) {
  1501. document.getElementById('wg-peer-modal-preshared').value = keys.private_key;
  1502. showToast('PSK Generated', 'Generated 256-bit preshared key', 'info');
  1503. }
  1504. } catch (err) {
  1505. showToast('Error', err.message, 'error');
  1506. }
  1507. }
  1508. function checkWGPeerKeyValidity() {
  1509. const ifaceName = document.getElementById('wg-peer-modal-iface').value;
  1510. const peerPubKey = document.getElementById('wg-peer-modal-pubkey').value.trim();
  1511. const warningEl = document.getElementById('wg-peer-key-warning');
  1512. if (!warningEl) return;
  1513. const targetIface = (state.wgInterfaces || []).find(i => i.name === ifaceName);
  1514. if (targetIface && targetIface.public_key && peerPubKey && targetIface.public_key === peerPubKey) {
  1515. warningEl.classList.remove('hidden');
  1516. } else {
  1517. warningEl.classList.add('hidden');
  1518. }
  1519. }
  1520. async function submitSaveWGPeer(e) {
  1521. e.preventDefault();
  1522. const origIface = document.getElementById('wg-peer-modal-edit-orig-iface').value.trim();
  1523. const origPubKey = document.getElementById('wg-peer-modal-edit-orig-pubkey').value.trim();
  1524. const iface = document.getElementById('wg-peer-modal-iface').value;
  1525. const name = document.getElementById('wg-peer-modal-name').value.trim();
  1526. const pub = document.getElementById('wg-peer-modal-pubkey').value.trim();
  1527. const allowed = document.getElementById('wg-peer-modal-allowedips').value
  1528. .split(',')
  1529. .map(s => s.trim())
  1530. .filter(s => s.length > 0);
  1531. const epHost = document.getElementById('wg-peer-modal-endpoint').value.trim();
  1532. const epPort = parseInt(document.getElementById('wg-peer-modal-port').value, 10) || 0;
  1533. const keepalive = parseInt(document.getElementById('wg-peer-modal-keepalive').value, 10) || 0;
  1534. const psk = document.getElementById('wg-peer-modal-preshared').value.trim();
  1535. const disabled = document.getElementById('wg-peer-modal-disabled').checked;
  1536. // Validation
  1537. const targetIface = (state.wgInterfaces || []).find(i => i.name === iface);
  1538. if (targetIface && targetIface.public_key === pub) {
  1539. showToast('Invalid Peer Key', 'Peer public key cannot be the same as the interface public key!', 'error');
  1540. return;
  1541. }
  1542. try {
  1543. const res = await fetch(`${API_BASE}/vpn/wireguard/peers`, {
  1544. method: 'POST',
  1545. headers: { 'Content-Type': 'application/json' },
  1546. body: JSON.stringify({
  1547. orig_interface: origIface,
  1548. orig_public_key: origPubKey,
  1549. interface: iface,
  1550. name,
  1551. public_key: pub,
  1552. allowed_ips: allowed,
  1553. endpoint_address: epHost,
  1554. endpoint_port: epPort,
  1555. persistent_keepalive: keepalive,
  1556. preshared_key: psk,
  1557. disabled
  1558. })
  1559. });
  1560. const data = await res.json();
  1561. if (res.ok) {
  1562. showToast('Peer Saved', `Peer ${name} saved on ${iface}`, 'success');
  1563. closeAddWGPeerModal();
  1564. loadWireGuard(false);
  1565. } else {
  1566. showToast('Error', data.error || 'Failed to save peer', 'error');
  1567. }
  1568. } catch (err) {
  1569. showToast('Error', err.message, 'error');
  1570. }
  1571. }
  1572. async function toggleWGPeerState(iface, pubkey, enable) {
  1573. try {
  1574. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/state`, {
  1575. method: 'POST',
  1576. headers: { 'Content-Type': 'application/json' },
  1577. body: JSON.stringify({ interface: iface, public_key: pubkey, enabled: enable })
  1578. });
  1579. const data = await res.json();
  1580. if (res.ok) {
  1581. showToast(enable ? 'Peer Enabled' : 'Peer Disabled', `Peer state updated on ${iface}`, 'info');
  1582. loadWireGuard(false);
  1583. } else {
  1584. showToast('Error', data.error || 'Failed to update peer state', 'error');
  1585. }
  1586. } catch (err) {
  1587. showToast('Error', err.message, 'error');
  1588. }
  1589. }
  1590. async function deleteWGPeer(iface, pubkey) {
  1591. if (!confirm(`Are you sure you want to remove peer from ${iface}?`)) return;
  1592. try {
  1593. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/delete`, {
  1594. method: 'POST',
  1595. headers: { 'Content-Type': 'application/json' },
  1596. body: JSON.stringify({ interface: iface, public_key: pubkey })
  1597. });
  1598. const data = await res.json();
  1599. if (res.ok) {
  1600. showToast('Peer Deleted', 'WireGuard peer removed', 'success');
  1601. loadWireGuard(false);
  1602. } else {
  1603. showToast('Error', data.error || 'Failed to remove peer', 'error');
  1604. }
  1605. } catch (err) {
  1606. showToast('Error', err.message, 'error');
  1607. }
  1608. }
  1609. // ======================== IPSec Multi-Tunnel ========================
  1610. async function loadIPSec(populateInputs = true) {
  1611. try {
  1612. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`);
  1613. const list = await res.json();
  1614. state.ipsecTunnels = Array.isArray(list) ? list : [];
  1615. const activeCount = state.ipsecTunnels.filter(t => t.running || t.status === 'ESTABLISHED').length;
  1616. const badge = document.getElementById('ipsec-sas-badge');
  1617. if (badge) badge.innerText = `${activeCount} Active SAs`;
  1618. const tbody = document.getElementById('ipsec-table-body');
  1619. const empty = document.getElementById('ipsec-empty');
  1620. if (!tbody) return;
  1621. tbody.innerHTML = '';
  1622. if (state.ipsecTunnels.length === 0) {
  1623. if (empty) empty.classList.remove('hidden');
  1624. } else {
  1625. if (empty) empty.classList.add('hidden');
  1626. state.ipsecTunnels.forEach(c => {
  1627. const isEstablished = c.running || c.status === 'ESTABLISHED';
  1628. const tr = document.createElement('tr');
  1629. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1630. tr.innerHTML = `
  1631. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isEstablished, c.disabled)}</td>
  1632. <td class="py-2.5 px-4 font-bold text-white">${c.name}</td>
  1633. <td class="py-2.5 px-4 text-emerald-400 font-mono">${c.local_subnet || '-'}</td>
  1634. <td class="py-2.5 px-4 text-slate-300 font-mono">${c.remote_addrs || '-'}</td>
  1635. <td class="py-2.5 px-4 text-cyan-400 font-mono">${c.remote_subnet || '-'}</td>
  1636. <td class="py-2.5 px-4 font-sans">
  1637. <span class="px-2 py-0.5 rounded-full text-[10px] font-semibold ${
  1638. isEstablished ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30' : 'bg-slate-800 text-slate-400'
  1639. }">${c.status || (isEstablished ? 'ESTABLISHED' : 'DISCONNECTED')}</span>
  1640. </td>
  1641. <td class="py-2.5 px-4 text-right space-x-2 font-sans">
  1642. ${isEstablished ? `
  1643. <button onclick="stopIPSecTunnel('${c.name}')" class="text-xs text-rose-400 hover:text-rose-300">Terminate</button>
  1644. ` : `
  1645. <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>
  1646. `}
  1647. <button onclick="toggleIPSecState('${c.name}', ${c.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1648. ${c.disabled ? 'Enable' : 'Disable'}
  1649. </button>
  1650. <button onclick="openEditIPSecModal('${c.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1651. <button onclick="deleteIPSecConn('${c.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1652. </td>
  1653. `;
  1654. tbody.appendChild(tr);
  1655. });
  1656. }
  1657. } catch (err) {
  1658. console.error('Failed to load IPSec:', err);
  1659. }
  1660. }
  1661. function openAddIPSecModal() {
  1662. document.getElementById('ipsec-modal-title').innerText = 'Configure IPSec IKEv2 Tunnel';
  1663. document.getElementById('ipsec-modal-name').value = `ipsec-${(state.ipsecTunnels || []).length + 1}`;
  1664. document.getElementById('ipsec-modal-name').readOnly = false;
  1665. document.getElementById('ipsec-modal-localts').value = '192.168.10.0/24';
  1666. document.getElementById('ipsec-modal-remotets').value = '192.168.20.0/24';
  1667. document.getElementById('ipsec-modal-remotegw').value = '';
  1668. document.getElementById('ipsec-modal-psk').value = '';
  1669. document.getElementById('ipsec-modal-ikeprop').value = 'aes256-sha256-modp2048,default';
  1670. document.getElementById('ipsec-modal-espprop').value = 'aes256-sha256-modp2048,default';
  1671. document.getElementById('ipsec-modal-autostart').checked = true;
  1672. document.getElementById('ipsec-modal-disabled').checked = false;
  1673. document.getElementById('ipsec-modal').classList.remove('hidden');
  1674. }
  1675. function openEditIPSecModal(name) {
  1676. const conn = (state.ipsecTunnels || []).find(c => c.name === name);
  1677. if (!conn) return;
  1678. document.getElementById('ipsec-modal-title').innerText = `Edit IPSec Tunnel: ${name}`;
  1679. document.getElementById('ipsec-modal-name').value = conn.name;
  1680. document.getElementById('ipsec-modal-name').readOnly = true;
  1681. document.getElementById('ipsec-modal-localts').value = conn.local_subnet || '';
  1682. document.getElementById('ipsec-modal-remotets').value = conn.remote_subnet || '';
  1683. document.getElementById('ipsec-modal-remotegw').value = conn.remote_addrs || '';
  1684. document.getElementById('ipsec-modal-psk').value = conn.preshared_key || '';
  1685. document.getElementById('ipsec-modal-ikeprop').value = conn.ike_proposals || 'aes256-sha256-modp2048,default';
  1686. document.getElementById('ipsec-modal-espprop').value = conn.esp_proposals || 'aes256-sha256-modp2048,default';
  1687. document.getElementById('ipsec-modal-autostart').checked = conn.auto_start ?? true;
  1688. document.getElementById('ipsec-modal-disabled').checked = !!conn.disabled;
  1689. document.getElementById('ipsec-modal').classList.remove('hidden');
  1690. }
  1691. function closeAddIPSecModal() {
  1692. document.getElementById('ipsec-modal').classList.add('hidden');
  1693. }
  1694. async function submitSaveIPSec(e) {
  1695. e.preventDefault();
  1696. const name = document.getElementById('ipsec-modal-name').value.trim();
  1697. const localts = document.getElementById('ipsec-modal-localts').value.trim();
  1698. const remotets = document.getElementById('ipsec-modal-remotets').value.trim();
  1699. const remotegw = document.getElementById('ipsec-modal-remotegw').value.trim();
  1700. const psk = document.getElementById('ipsec-modal-psk').value;
  1701. const ike = document.getElementById('ipsec-modal-ikeprop').value.trim();
  1702. const esp = document.getElementById('ipsec-modal-espprop').value.trim();
  1703. const autostart = document.getElementById('ipsec-modal-autostart').checked;
  1704. const disabled = document.getElementById('ipsec-modal-disabled').checked;
  1705. try {
  1706. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`, {
  1707. method: 'POST',
  1708. headers: { 'Content-Type': 'application/json' },
  1709. body: JSON.stringify({
  1710. name,
  1711. local_addrs: '%any',
  1712. remote_addrs: remotegw,
  1713. local_subnet: localts,
  1714. remote_subnet: remotets,
  1715. preshared_key: psk,
  1716. ike_proposals: ike,
  1717. esp_proposals: esp,
  1718. auto_start: autostart,
  1719. disabled
  1720. })
  1721. });
  1722. if (res.ok) {
  1723. showToast('IPSec Saved', `Tunnel ${name} configured`, 'success');
  1724. closeAddIPSecModal();
  1725. loadIPSec(false);
  1726. fetchData(false);
  1727. }
  1728. } catch (err) {
  1729. showToast('Error', err.message, 'error');
  1730. }
  1731. }
  1732. async function startIPSecTunnel(name) {
  1733. try {
  1734. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1735. if (res.ok) {
  1736. showToast('Initiating Tunnel', `Attempting SA handshake for ${name}...`, 'info');
  1737. setTimeout(() => loadIPSec(false), 2000);
  1738. }
  1739. } catch (err) {
  1740. showToast('Error', err.message, 'error');
  1741. }
  1742. }
  1743. async function stopIPSecTunnel(name) {
  1744. try {
  1745. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1746. if (res.ok) {
  1747. showToast('Terminated', `IPSec SA for ${name} closed`, 'info');
  1748. loadIPSec(false);
  1749. }
  1750. } catch (err) {
  1751. showToast('Error', err.message, 'error');
  1752. }
  1753. }
  1754. async function toggleIPSecState(name, enable) {
  1755. try {
  1756. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/state`, {
  1757. method: 'POST',
  1758. headers: { 'Content-Type': 'application/json' },
  1759. body: JSON.stringify({ enabled: enable })
  1760. });
  1761. if (res.ok) {
  1762. showToast(enable ? 'Enabled' : 'Disabled', `IPSec tunnel ${name} updated`, 'info');
  1763. loadIPSec(false);
  1764. }
  1765. } catch (err) {
  1766. showToast('Error', err.message, 'error');
  1767. }
  1768. }
  1769. async function deleteIPSecConn(name) {
  1770. if (!confirm(`Are you sure you want to delete IPSec tunnel ${name}?`)) return;
  1771. try {
  1772. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1773. if (res.ok) {
  1774. showToast('Deleted', `IPSec connection ${name} removed`, 'success');
  1775. loadIPSec(false);
  1776. fetchData(false);
  1777. }
  1778. } catch (err) {
  1779. showToast('Error', err.message, 'error');
  1780. }
  1781. }
  1782. // ======================== L2TP Multi-Instance ========================
  1783. async function loadL2TP(populateInputs = true) {
  1784. try {
  1785. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`);
  1786. const list = await res.json();
  1787. state.l2tpList = Array.isArray(list) ? list : [];
  1788. const badge = document.getElementById('l2tp-count-badge');
  1789. if (badge) badge.innerText = `${state.l2tpList.length} Client${state.l2tpList.length !== 1 ? 's' : ''}`;
  1790. const tbody = document.getElementById('l2tp-table-body');
  1791. const empty = document.getElementById('l2tp-empty');
  1792. if (!tbody) return;
  1793. tbody.innerHTML = '';
  1794. if (state.l2tpList.length === 0) {
  1795. if (empty) empty.classList.remove('hidden');
  1796. } else {
  1797. if (empty) empty.classList.add('hidden');
  1798. state.l2tpList.forEach(inst => {
  1799. const tr = document.createElement('tr');
  1800. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1801. tr.innerHTML = `
  1802. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1803. <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
  1804. <td class="py-2.5 px-3 text-cyan-400 font-mono">${inst.connect_to}</td>
  1805. <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
  1806. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
  1807. <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
  1808. <td class="py-2.5 px-3 text-center">
  1809. <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'}">
  1810. ${inst.default_route ? 'Yes' : 'No'}
  1811. </span>
  1812. </td>
  1813. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1814. ${inst.running ? `
  1815. <button onclick="disconnectL2TPInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1816. ` : `
  1817. <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>
  1818. `}
  1819. <button onclick="toggleL2TPState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1820. ${inst.disabled ? 'Enable' : 'Disable'}
  1821. </button>
  1822. <button onclick="openEditL2TPModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1823. <button onclick="deleteL2TPInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1824. </td>
  1825. `;
  1826. tbody.appendChild(tr);
  1827. });
  1828. }
  1829. } catch (err) {
  1830. console.error('Failed to load L2TP:', err);
  1831. }
  1832. }
  1833. function openAddL2TPModal() {
  1834. document.getElementById('l2tp-modal-title').innerText = 'Add L2TP Client Interface';
  1835. document.getElementById('l2tp-modal-name').value = `l2tp-out${(state.l2tpList || []).length + 1}`;
  1836. document.getElementById('l2tp-modal-name').readOnly = false;
  1837. document.getElementById('l2tp-modal-server').value = '';
  1838. document.getElementById('l2tp-modal-user').value = '';
  1839. document.getElementById('l2tp-modal-pass').value = '';
  1840. document.getElementById('l2tp-modal-ipsec').value = '';
  1841. document.getElementById('l2tp-modal-defroute').checked = true;
  1842. document.getElementById('l2tp-modal-disabled').checked = false;
  1843. document.getElementById('l2tp-modal').classList.remove('hidden');
  1844. }
  1845. function openEditL2TPModal(name) {
  1846. const inst = (state.l2tpList || []).find(i => i.name === name);
  1847. if (!inst) return;
  1848. document.getElementById('l2tp-modal-title').innerText = `Edit L2TP Client: ${name}`;
  1849. document.getElementById('l2tp-modal-name').value = inst.name;
  1850. document.getElementById('l2tp-modal-name').readOnly = true;
  1851. document.getElementById('l2tp-modal-server').value = inst.connect_to || '';
  1852. document.getElementById('l2tp-modal-user').value = inst.username || '';
  1853. document.getElementById('l2tp-modal-pass').value = inst.password || '';
  1854. document.getElementById('l2tp-modal-ipsec').value = inst.ipsec_secret || '';
  1855. document.getElementById('l2tp-modal-defroute').checked = inst.default_route ?? true;
  1856. document.getElementById('l2tp-modal-disabled').checked = !!inst.disabled;
  1857. document.getElementById('l2tp-modal').classList.remove('hidden');
  1858. }
  1859. function closeL2TPModal() {
  1860. document.getElementById('l2tp-modal').classList.add('hidden');
  1861. }
  1862. async function submitSaveL2TP(e) {
  1863. e.preventDefault();
  1864. const name = document.getElementById('l2tp-modal-name').value.trim();
  1865. const server = document.getElementById('l2tp-modal-server').value.trim();
  1866. const user = document.getElementById('l2tp-modal-user').value.trim();
  1867. const pass = document.getElementById('l2tp-modal-pass').value;
  1868. const ipsec = document.getElementById('l2tp-modal-ipsec').value;
  1869. const defRoute = document.getElementById('l2tp-modal-defroute').checked;
  1870. const disabled = document.getElementById('l2tp-modal-disabled').checked;
  1871. try {
  1872. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`, {
  1873. method: 'POST',
  1874. headers: { 'Content-Type': 'application/json' },
  1875. body: JSON.stringify({
  1876. name,
  1877. connect_to: server,
  1878. username: user,
  1879. password: pass,
  1880. ipsec_secret: ipsec,
  1881. default_route: defRoute,
  1882. disabled
  1883. })
  1884. });
  1885. if (res.ok) {
  1886. showToast('L2TP Saved', `Client ${name} configuration saved`, 'success');
  1887. closeL2TPModal();
  1888. loadL2TP(false);
  1889. fetchData(false);
  1890. }
  1891. } catch (err) {
  1892. showToast('Error', err.message, 'error');
  1893. }
  1894. }
  1895. async function connectL2TPInstance(name) {
  1896. try {
  1897. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1898. if (res.ok) {
  1899. showToast('Connecting', `Dialing L2TP ${name}...`, 'info');
  1900. setTimeout(() => loadL2TP(false), 2000);
  1901. }
  1902. } catch (err) {
  1903. showToast('Error', err.message, 'error');
  1904. }
  1905. }
  1906. async function disconnectL2TPInstance(name) {
  1907. try {
  1908. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1909. if (res.ok) {
  1910. showToast('Disconnected', `L2TP tunnel ${name} terminated`, 'info');
  1911. loadL2TP(false);
  1912. }
  1913. } catch (err) {
  1914. showToast('Error', err.message, 'error');
  1915. }
  1916. }
  1917. async function toggleL2TPState(name, enable) {
  1918. try {
  1919. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/state`, {
  1920. method: 'POST',
  1921. headers: { 'Content-Type': 'application/json' },
  1922. body: JSON.stringify({ enabled: enable })
  1923. });
  1924. if (res.ok) {
  1925. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1926. loadL2TP(false);
  1927. }
  1928. } catch (err) {
  1929. showToast('Error', err.message, 'error');
  1930. }
  1931. }
  1932. async function deleteL2TPInstance(name) {
  1933. if (!confirm(`Are you sure you want to delete L2TP client ${name}?`)) return;
  1934. try {
  1935. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1936. if (res.ok) {
  1937. showToast('Deleted', `L2TP client ${name} removed`, 'success');
  1938. loadL2TP(false);
  1939. fetchData(false);
  1940. }
  1941. } catch (err) {
  1942. showToast('Error', err.message, 'error');
  1943. }
  1944. }
  1945. // ======================== PPTP Multi-Instance ========================
  1946. async function loadPPTP(populateInputs = true) {
  1947. try {
  1948. const res = await fetch(`${API_BASE}/vpn/pptp/clients`);
  1949. const list = await res.json();
  1950. state.pptpList = Array.isArray(list) ? list : [];
  1951. const badge = document.getElementById('pptp-count-badge');
  1952. if (badge) badge.innerText = `${state.pptpList.length} Client${state.pptpList.length !== 1 ? 's' : ''}`;
  1953. const tbody = document.getElementById('pptp-table-body');
  1954. const empty = document.getElementById('pptp-empty');
  1955. if (!tbody) return;
  1956. tbody.innerHTML = '';
  1957. if (state.pptpList.length === 0) {
  1958. if (empty) empty.classList.remove('hidden');
  1959. } else {
  1960. if (empty) empty.classList.add('hidden');
  1961. state.pptpList.forEach(inst => {
  1962. const tr = document.createElement('tr');
  1963. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1964. tr.innerHTML = `
  1965. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1966. <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
  1967. <td class="py-2.5 px-3 text-purple-400 font-mono">${inst.connect_to}</td>
  1968. <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
  1969. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
  1970. <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
  1971. <td class="py-2.5 px-3 text-center">
  1972. <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'}">
  1973. ${inst.require_mppe ? 'MPPE-128' : 'None'}
  1974. </span>
  1975. </td>
  1976. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1977. ${inst.running ? `
  1978. <button onclick="disconnectPPTPInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1979. ` : `
  1980. <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>
  1981. `}
  1982. <button onclick="togglePPTPState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1983. ${inst.disabled ? 'Enable' : 'Disable'}
  1984. </button>
  1985. <button onclick="openEditPPTPModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1986. <button onclick="deletePPTPInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1987. </td>
  1988. `;
  1989. tbody.appendChild(tr);
  1990. });
  1991. }
  1992. } catch (err) {
  1993. console.error('Failed to load PPTP:', err);
  1994. }
  1995. }
  1996. function openAddPPTPModal() {
  1997. document.getElementById('pptp-modal-title').innerText = 'Add PPTP Client Interface';
  1998. document.getElementById('pptp-modal-name').value = `pptp-out${(state.pptpList || []).length + 1}`;
  1999. document.getElementById('pptp-modal-name').readOnly = false;
  2000. document.getElementById('pptp-modal-server').value = '';
  2001. document.getElementById('pptp-modal-user').value = '';
  2002. document.getElementById('pptp-modal-pass').value = '';
  2003. document.getElementById('pptp-modal-mppe').checked = true;
  2004. document.getElementById('pptp-modal-defroute').checked = true;
  2005. document.getElementById('pptp-modal-disabled').checked = false;
  2006. document.getElementById('pptp-modal').classList.remove('hidden');
  2007. }
  2008. function openEditPPTPModal(name) {
  2009. const inst = (state.pptpList || []).find(i => i.name === name);
  2010. if (!inst) return;
  2011. document.getElementById('pptp-modal-title').innerText = `Edit PPTP Client: ${name}`;
  2012. document.getElementById('pptp-modal-name').value = inst.name;
  2013. document.getElementById('pptp-modal-name').readOnly = true;
  2014. document.getElementById('pptp-modal-server').value = inst.connect_to || '';
  2015. document.getElementById('pptp-modal-user').value = inst.username || '';
  2016. document.getElementById('pptp-modal-pass').value = inst.password || '';
  2017. document.getElementById('pptp-modal-mppe').checked = inst.require_mppe ?? true;
  2018. document.getElementById('pptp-modal-defroute').checked = inst.default_route ?? true;
  2019. document.getElementById('pptp-modal-disabled').checked = !!inst.disabled;
  2020. document.getElementById('pptp-modal').classList.remove('hidden');
  2021. }
  2022. function closePPTPModal() {
  2023. document.getElementById('pptp-modal').classList.add('hidden');
  2024. }
  2025. async function submitSavePPTP(e) {
  2026. e.preventDefault();
  2027. const name = document.getElementById('pptp-modal-name').value.trim();
  2028. const server = document.getElementById('pptp-modal-server').value.trim();
  2029. const user = document.getElementById('pptp-modal-user').value.trim();
  2030. const pass = document.getElementById('pptp-modal-pass').value;
  2031. const mppe = document.getElementById('pptp-modal-mppe').checked;
  2032. const defRoute = document.getElementById('pptp-modal-defroute').checked;
  2033. const disabled = document.getElementById('pptp-modal-disabled').checked;
  2034. try {
  2035. const res = await fetch(`${API_BASE}/vpn/pptp/clients`, {
  2036. method: 'POST',
  2037. headers: { 'Content-Type': 'application/json' },
  2038. body: JSON.stringify({
  2039. name,
  2040. connect_to: server,
  2041. username: user,
  2042. password: pass,
  2043. require_mppe: mppe,
  2044. default_route: defRoute,
  2045. auto_reconnect: true,
  2046. disabled
  2047. })
  2048. });
  2049. if (res.ok) {
  2050. showToast('PPTP Saved', `Client ${name} configuration saved`, 'success');
  2051. closePPTPModal();
  2052. loadPPTP(false);
  2053. fetchData(false);
  2054. }
  2055. } catch (err) {
  2056. showToast('Error', err.message, 'error');
  2057. }
  2058. }
  2059. async function connectPPTPInstance(name) {
  2060. try {
  2061. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2062. if (res.ok) {
  2063. showToast('Connecting', `Dialing PPTP ${name}...`, 'info');
  2064. setTimeout(() => loadPPTP(false), 2000);
  2065. }
  2066. } catch (err) {
  2067. showToast('Error', err.message, 'error');
  2068. }
  2069. }
  2070. async function disconnectPPTPInstance(name) {
  2071. try {
  2072. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2073. if (res.ok) {
  2074. showToast('Disconnected', `PPTP tunnel ${name} terminated`, 'info');
  2075. loadPPTP(false);
  2076. }
  2077. } catch (err) {
  2078. showToast('Error', err.message, 'error');
  2079. }
  2080. }
  2081. async function togglePPTPState(name, enable) {
  2082. try {
  2083. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/state`, {
  2084. method: 'POST',
  2085. headers: { 'Content-Type': 'application/json' },
  2086. body: JSON.stringify({ enabled: enable })
  2087. });
  2088. if (res.ok) {
  2089. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2090. loadPPTP(false);
  2091. }
  2092. } catch (err) {
  2093. showToast('Error', err.message, 'error');
  2094. }
  2095. }
  2096. async function deletePPTPInstance(name) {
  2097. if (!confirm(`Are you sure you want to delete PPTP client ${name}?`)) return;
  2098. try {
  2099. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2100. if (res.ok) {
  2101. showToast('Deleted', `PPTP client ${name} removed`, 'success');
  2102. loadPPTP(false);
  2103. fetchData(false);
  2104. }
  2105. } catch (err) {
  2106. showToast('Error', err.message, 'error');
  2107. }
  2108. }
  2109. // ---------------- Modal & Helper Functions ----------------
  2110. function openVlanModal(defaultParent = '') {
  2111. const select = document.getElementById('vlan-parent');
  2112. select.innerHTML = '';
  2113. const allIfaces = state.interfaces || [];
  2114. const eligible = allIfaces.filter(i => supportsVLAN(i));
  2115. if (eligible.length === 0) {
  2116. const opt = document.createElement('option');
  2117. opt.value = '';
  2118. opt.innerText = 'No VLAN-capable interfaces available';
  2119. select.appendChild(opt);
  2120. } else {
  2121. eligible.forEach(i => {
  2122. const opt = document.createElement('option');
  2123. opt.value = i.name;
  2124. opt.innerText = `${i.name} (${i.role || i.type || 'Ethernet'} - ${i.state})`;
  2125. if (i.name === defaultParent) opt.selected = true;
  2126. select.appendChild(opt);
  2127. });
  2128. }
  2129. document.getElementById('vlan-id').value = '';
  2130. document.getElementById('vlan-name').value = '';
  2131. document.getElementById('vlan-ip').value = '';
  2132. document.getElementById('vlan-desc').value = '';
  2133. autoSuggestVlanName();
  2134. document.getElementById('vlan-modal').classList.remove('hidden');
  2135. }
  2136. function closeVlanModal() {
  2137. document.getElementById('vlan-modal').classList.add('hidden');
  2138. }
  2139. function autoSuggestVlanName() {
  2140. const parent = document.getElementById('vlan-parent').value;
  2141. if (!parent) return;
  2142. const id = document.getElementById('vlan-id').value;
  2143. const nameInput = document.getElementById('vlan-name');
  2144. if (parent && id) nameInput.placeholder = `${parent}.${id}`;
  2145. }
  2146. function setSubnetPreset(cidr) {
  2147. const ipInput = document.getElementById('vlan-ip');
  2148. const id = document.getElementById('vlan-id').value || '10';
  2149. ipInput.value = `192.168.${id}.1${cidr}`;
  2150. }
  2151. async function submitCreateVlan(e) {
  2152. e.preventDefault();
  2153. const btn = document.getElementById('vlan-submit-btn');
  2154. btn.disabled = true;
  2155. btn.innerText = 'Creating...';
  2156. const parent = document.getElementById('vlan-parent').value;
  2157. if (!parent) {
  2158. showToast('Error', 'Please select a valid VLAN-capable parent interface', 'error');
  2159. btn.disabled = false;
  2160. btn.innerText = 'Create VLAN';
  2161. return;
  2162. }
  2163. const id = parseInt(document.getElementById('vlan-id').value, 10);
  2164. const name = document.getElementById('vlan-name').value.trim();
  2165. const ip = document.getElementById('vlan-ip').value.trim();
  2166. const role = document.getElementById('vlan-role').value;
  2167. const desc = document.getElementById('vlan-desc').value.trim();
  2168. try {
  2169. const res = await fetch(`${API_BASE}/vlans`, {
  2170. method: 'POST',
  2171. headers: { 'Content-Type': 'application/json' },
  2172. body: JSON.stringify({
  2173. parent_name: parent,
  2174. vlan_id: id,
  2175. name: name,
  2176. ip_address: ip,
  2177. role: role,
  2178. description: desc,
  2179. mtu: 1500,
  2180. auto_up: true
  2181. })
  2182. });
  2183. const data = await res.json();
  2184. if (res.ok) {
  2185. showToast('VLAN Created', `Created ${data.name} (VLAN ${data.vlan_id})`, 'success');
  2186. state.expandedParents.add(parent);
  2187. closeVlanModal();
  2188. await fetchData(true);
  2189. if (state.activeTab !== 'interfaces') navigate('interfaces');
  2190. } else {
  2191. showToast('Creation Failed', data.message || 'Failed to create VLAN', 'error');
  2192. }
  2193. } catch (err) {
  2194. showToast('Error', err.message, 'error');
  2195. } finally {
  2196. btn.disabled = false;
  2197. btn.innerText = 'Create VLAN';
  2198. }
  2199. }
  2200. async function confirmDeleteVlan(name) {
  2201. if (!confirm(`Delete VLAN interface ${name}?`)) return;
  2202. try {
  2203. const res = await fetch(`${API_BASE}/vlans/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2204. if (res.ok) {
  2205. showToast('VLAN Deleted', `Interface ${name} removed`, 'success');
  2206. closeIfaceModal();
  2207. fetchData(true);
  2208. }
  2209. } catch (err) {
  2210. showToast('Error', err.message, 'error');
  2211. }
  2212. }
  2213. function openIfaceModal(name) {
  2214. const iface = (state.interfaces || []).find(i => i.name === name);
  2215. if (!iface) return;
  2216. state.currentModalIface = iface.name;
  2217. document.getElementById('modal-iface-name').innerText = iface.name;
  2218. document.getElementById('modal-iface-badge').innerText = iface.is_vlan ? `VLAN ${iface.vlan_id}` : iface.type;
  2219. document.getElementById('modal-iface-mtu').value = iface.mtu;
  2220. document.getElementById('modal-iface-role').value = iface.role || 'LAN';
  2221. document.getElementById('modal-iface-desc').value = iface.description || '';
  2222. const delBtn = document.getElementById('modal-delete-vlan-btn');
  2223. if (iface.is_vlan) {
  2224. delBtn.classList.remove('hidden');
  2225. } else {
  2226. delBtn.classList.add('hidden');
  2227. }
  2228. renderModalIPs(iface);
  2229. document.getElementById('iface-modal').classList.remove('hidden');
  2230. }
  2231. function renderModalIPs(iface) {
  2232. const container = document.getElementById('modal-ip-list');
  2233. container.innerHTML = '';
  2234. const addrs = [...(iface.ipv4 || []), ...(iface.ipv6 || [])];
  2235. if (addrs.length === 0) {
  2236. container.innerHTML = `<span class="text-slate-500 text-xs font-sans">No IP addresses currently bound</span>`;
  2237. return;
  2238. }
  2239. addrs.forEach(addr => {
  2240. const row = document.createElement('div');
  2241. row.className = 'flex items-center justify-between p-2 rounded bg-slate-900 border border-slate-800';
  2242. row.innerHTML = `
  2243. <span class="text-white">${addr}</span>
  2244. <button onclick="removeInterfaceIP('${addr}')" class="text-[11px] text-rose-400 hover:text-rose-300 font-sans">Remove</button>
  2245. `;
  2246. container.appendChild(row);
  2247. });
  2248. }
  2249. function closeIfaceModal() {
  2250. document.getElementById('iface-modal').classList.add('hidden');
  2251. state.currentModalIface = null;
  2252. }
  2253. async function setIfaceState(name, newState) {
  2254. await toggleInterfaceState(name, newState);
  2255. const updated = (state.interfaces || []).find(i => i.name === name);
  2256. if (updated) openIfaceModal(name);
  2257. }
  2258. async function applyMTU() {
  2259. const mtu = parseInt(document.getElementById('modal-iface-mtu').value, 10);
  2260. try {
  2261. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/mtu`, {
  2262. method: 'POST',
  2263. headers: { 'Content-Type': 'application/json' },
  2264. body: JSON.stringify({ mtu })
  2265. });
  2266. if (res.ok) {
  2267. showToast('MTU Applied', `Set MTU to ${mtu} on ${state.currentModalIface}`, 'success');
  2268. fetchData(false);
  2269. }
  2270. } catch (err) {
  2271. showToast('Error', err.message, 'error');
  2272. }
  2273. }
  2274. async function addInterfaceIP() {
  2275. const ip = document.getElementById('modal-new-ip').value.trim();
  2276. if (!ip) return;
  2277. try {
  2278. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  2279. method: 'POST',
  2280. headers: { 'Content-Type': 'application/json' },
  2281. body: JSON.stringify({ ip })
  2282. });
  2283. if (res.ok) {
  2284. showToast('IP Added', `Bound ${ip} to ${state.currentModalIface}`, 'success');
  2285. document.getElementById('modal-new-ip').value = '';
  2286. await fetchData(false);
  2287. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  2288. if (iface) renderModalIPs(iface);
  2289. } else {
  2290. const err = await res.json();
  2291. showToast('Error', err.error || err.message || 'Failed to add IP address', 'error');
  2292. }
  2293. } catch (err) {
  2294. showToast('Error', err.message, 'error');
  2295. }
  2296. }
  2297. async function removeInterfaceIP(ip) {
  2298. if (!confirm(`Remove IP ${ip}?`)) return;
  2299. try {
  2300. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  2301. method: 'DELETE',
  2302. headers: { 'Content-Type': 'application/json' },
  2303. body: JSON.stringify({ ip })
  2304. });
  2305. if (res.ok) {
  2306. showToast('IP Removed', `Removed ${ip}`, 'success');
  2307. await fetchData(false);
  2308. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  2309. if (iface) renderModalIPs(iface);
  2310. }
  2311. } catch (err) {
  2312. showToast('Error', err.message, 'error');
  2313. }
  2314. }
  2315. async function saveInterfaceMetadata() {
  2316. const role = document.getElementById('modal-iface-role').value;
  2317. const desc = document.getElementById('modal-iface-desc').value.trim();
  2318. try {
  2319. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/metadata`, {
  2320. method: 'POST',
  2321. headers: { 'Content-Type': 'application/json' },
  2322. body: JSON.stringify({ role, description: desc })
  2323. });
  2324. if (res.ok) {
  2325. showToast('Saved', 'Metadata updated', 'success');
  2326. closeIfaceModal();
  2327. fetchData(false);
  2328. }
  2329. } catch (err) {
  2330. showToast('Error', err.message, 'error');
  2331. }
  2332. }
  2333. // ======================== MIKROTIK FIREWALL (/ip firewall) ========================
  2334. state.fwSubTab = 'filter';
  2335. state.routesSubTab = 'routes';
  2336. function renderRuleFlag(disabled, hasComment) {
  2337. let flags = '';
  2338. if (disabled) flags += '<span class="text-rose-400 font-bold" title="Disabled">X</span>';
  2339. if (hasComment) flags += '<span class="text-amber-400 font-bold ml-1" title="Has Comment">C</span>';
  2340. return flags || '<span class="text-slate-600">-</span>';
  2341. }
  2342. function renderActionBadge(action) {
  2343. const act = (action || '').toLowerCase();
  2344. let color = 'bg-slate-800 text-slate-300';
  2345. if (act === 'accept') color = 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30';
  2346. else if (act === 'drop' || act === 'reject') color = 'bg-rose-500/20 text-rose-300 border border-rose-500/30';
  2347. else if (act === 'masquerade' || act === 'src-nat' || act === 'dst-nat') color = 'bg-amber-500/20 text-amber-300 border border-amber-500/30';
  2348. else if (act.startsWith('mark-')) color = 'bg-purple-500/20 text-purple-300 border border-purple-500/30';
  2349. else if (act === 'log') color = 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30';
  2350. return `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold ${color}">${action}</span>`;
  2351. }
  2352. function switchFWSubTab(tab) {
  2353. state.fwSubTab = tab;
  2354. const tabs = ['filter', 'nat', 'mangle', 'addrlist', 'geo', 'connections'];
  2355. tabs.forEach(t => {
  2356. const panel = document.getElementById(`fw-subtab-${t}`);
  2357. const btn = document.getElementById(`fw-subtab-btn-${t}`);
  2358. if (panel) {
  2359. if (t === tab) panel.classList.remove('hidden');
  2360. else panel.classList.add('hidden');
  2361. }
  2362. if (btn) {
  2363. if (t === tab) {
  2364. 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';
  2365. } else {
  2366. 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';
  2367. }
  2368. }
  2369. });
  2370. const addBtn = document.getElementById('fw-primary-add-btn');
  2371. if (addBtn) {
  2372. if (tab === 'filter') addBtn.innerHTML = '<span>+ Add Filter Rule</span>';
  2373. else if (tab === 'nat') addBtn.innerHTML = '<span>+ Add NAT Rule</span>';
  2374. else if (tab === 'mangle') addBtn.innerHTML = '<span>+ Add Mangle Rule</span>';
  2375. else if (tab === 'addrlist') addBtn.innerHTML = '<span>+ Add Address List</span>';
  2376. else if (tab === 'geo') addBtn.innerHTML = '<span>⚙️ Schedule Settings</span>';
  2377. else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
  2378. }
  2379. if (tab === 'geo') loadGeoIP();
  2380. if (tab === 'connections') loadConnections();
  2381. setTimeout(initTableSorting, 50);
  2382. }
  2383. function openCurrentFWModal() {
  2384. if (state.fwSubTab === 'filter') openAddFilterModal();
  2385. else if (state.fwSubTab === 'nat') openAddNATModal();
  2386. else if (state.fwSubTab === 'mangle') openAddMangleModal();
  2387. else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
  2388. else if (state.fwSubTab === 'geo') openGeoIntervalModal();
  2389. else if (state.fwSubTab === 'connections') loadConnections();
  2390. }
  2391. async function loadFirewall(populateDropdowns = true) {
  2392. try {
  2393. const [summaryRes, filterRes, natRes, mangleRes, addrlistRes, geoStatusRes, geoCountriesRes] = await Promise.all([
  2394. fetch(`${API_BASE}/firewall/summary`),
  2395. fetch(`${API_BASE}/firewall/filter`),
  2396. fetch(`${API_BASE}/firewall/nat`),
  2397. fetch(`${API_BASE}/firewall/mangle`),
  2398. fetch(`${API_BASE}/firewall/address-lists`),
  2399. fetch(`${API_BASE}/firewall/geoip/status`),
  2400. fetch(`${API_BASE}/firewall/geoip/countries`)
  2401. ]);
  2402. if (summaryRes.ok) state.fwSummary = await summaryRes.json();
  2403. if (filterRes.ok) state.filterRules = await filterRes.json();
  2404. if (natRes.ok) state.natRules = await natRes.json();
  2405. if (mangleRes.ok) state.mangleRules = await mangleRes.json();
  2406. if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
  2407. if (geoStatusRes.ok) state.geoStatus = await geoStatusRes.json();
  2408. if (geoCountriesRes.ok) state.geoCountries = await geoCountriesRes.json();
  2409. // Badges
  2410. const bFilter = document.getElementById('fw-badge-filter');
  2411. if (bFilter) bFilter.innerText = (state.filterRules || []).length;
  2412. const bNat = document.getElementById('fw-badge-nat');
  2413. if (bNat) bNat.innerText = (state.natRules || []).length;
  2414. const bMangle = document.getElementById('fw-badge-mangle');
  2415. if (bMangle) bMangle.innerText = (state.mangleRules || []).length;
  2416. const bAddr = document.getElementById('fw-badge-addrlist');
  2417. if (bAddr) bAddr.innerText = (state.addressLists || []).length;
  2418. const bGeo = document.getElementById('fw-badge-geo');
  2419. if (bGeo) bGeo.innerText = state.geoStatus?.enabled_count || 0;
  2420. renderFilterRules();
  2421. renderNATRules();
  2422. renderMangleRules();
  2423. renderAddressLists();
  2424. renderGeoCountries();
  2425. if (state.fwSubTab === 'connections') {
  2426. loadConnections();
  2427. }
  2428. } catch (err) {
  2429. console.error('Failed to load firewall:', err);
  2430. }
  2431. }
  2432. // ----------------- Filter Rules -----------------
  2433. function renderFilterRules() {
  2434. const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
  2435. const tbody = document.getElementById('filter-table-body');
  2436. const empty = document.getElementById('filter-empty');
  2437. if (!tbody) return;
  2438. tbody.innerHTML = '';
  2439. const rules = (state.filterRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2440. document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
  2441. if (rules.length === 0) {
  2442. empty?.classList.remove('hidden');
  2443. return;
  2444. }
  2445. empty?.classList.add('hidden');
  2446. rules.forEach((r, idx) => {
  2447. const tr = document.createElement('tr');
  2448. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2449. const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
  2450. const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
  2451. let actionExtra = '';
  2452. if (r.action === 'reject') {
  2453. actionExtra = `<span class="block text-[10px] text-rose-300 font-mono mt-0.5">(${r.reject_with || 'icmp-net-unreach'})</span>`;
  2454. } else if (r.action === 'jump') {
  2455. actionExtra = `<span class="block text-[10px] text-yellow-300 font-mono mt-0.5">&rarr; ${r.jump_target || '-'}</span>`;
  2456. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  2457. actionExtra = `<span class="block text-[10px] text-emerald-300 font-mono mt-0.5">&rarr; ${r.address_list || '-'}</span>`;
  2458. } else if (r.action === 'log' && r.log_prefix) {
  2459. actionExtra = `<span class="block text-[10px] text-slate-400 font-mono mt-0.5">${r.log_prefix}</span>`;
  2460. }
  2461. tr.innerHTML = `
  2462. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  2463. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  2464. <td class="py-2.5 px-3 font-bold text-white">${r.chain}</td>
  2465. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  2466. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  2467. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}</td>
  2468. <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
  2469. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  2470. <td class="py-2.5 px-3">${renderActionBadge(r.action)}${actionExtra}</td>
  2471. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2472. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2473. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2474. </td>
  2475. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2476. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2477. <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2478. <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2479. <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>
  2480. <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2481. <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2482. </td>
  2483. `;
  2484. tbody.appendChild(tr);
  2485. });
  2486. }
  2487. function formatTarget(addr, list, geo) {
  2488. const parts = [];
  2489. if (addr) parts.push(`<span>${addr}</span>`);
  2490. if (list) {
  2491. const inv = list.startsWith('!') ? '!' : '';
  2492. const clean = list.replace(/^!/, '');
  2493. 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>`);
  2494. }
  2495. if (geo) {
  2496. const inv = geo.startsWith('!') ? '!' : '';
  2497. const clean = geo.replace(/^!/, '').replace(/^geo:/, '');
  2498. 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>`);
  2499. }
  2500. if (parts.length === 0) return '<span class="text-slate-600">0.0.0.0/0</span>';
  2501. return parts.join(' ');
  2502. }
  2503. function populateInterfaceSelect(selectId, currentVal = '') {
  2504. const sel = document.getElementById(selectId);
  2505. if (!sel) return;
  2506. sel.innerHTML = '<option value="">(Any Interface)</option>';
  2507. (state.interfaces || []).forEach(i => {
  2508. const opt = document.createElement('option');
  2509. opt.value = i.name;
  2510. opt.innerText = `${i.name} (${i.role || i.type})`;
  2511. if (i.name === currentVal) opt.selected = true;
  2512. sel.appendChild(opt);
  2513. });
  2514. }
  2515. function populateAddressListSelect(selectId, currentVal = '') {
  2516. const sel = document.getElementById(selectId);
  2517. if (!sel) return;
  2518. sel.innerHTML = '<option value="">(None)</option>';
  2519. const cleanVal = (currentVal || '').replace(/^!/, '');
  2520. const customNames = Array.from(new Set((state.addressLists || []).map(a => a.name))).sort();
  2521. customNames.forEach(name => {
  2522. const count = (state.addressLists || []).filter(a => a.name === name).length;
  2523. const opt = document.createElement('option');
  2524. opt.value = name;
  2525. opt.innerText = `${name} (${count} entries)`;
  2526. if (name === cleanVal) opt.selected = true;
  2527. sel.appendChild(opt);
  2528. });
  2529. if (cleanVal && !sel.querySelector(`option[value="${cleanVal}"]`)) {
  2530. const opt = document.createElement('option');
  2531. opt.value = cleanVal;
  2532. opt.innerText = cleanVal;
  2533. opt.selected = true;
  2534. sel.appendChild(opt);
  2535. }
  2536. populateCommonAddrListDatalist();
  2537. }
  2538. function populateCommonAddrListDatalist() {
  2539. const dl = document.getElementById('fw-addrlist-datalist');
  2540. if (!dl) return;
  2541. dl.innerHTML = '';
  2542. const names = Array.from(new Set((state.addressLists || []).map(a => a.name).filter(Boolean))).sort();
  2543. names.forEach(name => {
  2544. const opt = document.createElement('option');
  2545. opt.value = name;
  2546. dl.appendChild(opt);
  2547. });
  2548. }
  2549. function populateGeoIPSelect(selectId, currentVal = '') {
  2550. const sel = document.getElementById(selectId);
  2551. if (!sel) return;
  2552. sel.innerHTML = '<option value="">(None)</option>';
  2553. const cleanVal = (currentVal || '').replace(/^!/, '').replace(/^geo:/, '').toUpperCase();
  2554. // Presets optgroup
  2555. const grpPresets = document.createElement('optgroup');
  2556. grpPresets.label = '⚡ Regional Presets';
  2557. const presets = [
  2558. { code: 'EU', label: '🇪🇺 European Union (EU - 27 countries)' },
  2559. { code: 'BALKANS', label: '🏛️ Balkans (GR, CY, BG, RO, AL, etc.)' },
  2560. { code: 'BLOCKLIST', label: '🛡️ High-Risk Blocklist (CN, RU, IR, KP, BY)' }
  2561. ];
  2562. presets.forEach(p => {
  2563. const opt = document.createElement('option');
  2564. opt.value = p.code;
  2565. opt.innerText = p.label;
  2566. if (p.code === cleanVal) opt.selected = true;
  2567. grpPresets.appendChild(opt);
  2568. });
  2569. sel.appendChild(grpPresets);
  2570. // All Countries optgroup
  2571. const grpCountries = document.createElement('optgroup');
  2572. grpCountries.label = '🌍 All Countries';
  2573. const countries = (state.geoCountries || []).slice().sort((a, b) => a.name.localeCompare(b.name));
  2574. countries.forEach(c => {
  2575. const opt = document.createElement('option');
  2576. opt.value = c.code;
  2577. const subnetsInfo = c.subnet_count ? ` [${c.subnet_count.toLocaleString()} subnets]` : '';
  2578. opt.innerText = `${c.name} (${c.code})${subnetsInfo}`;
  2579. if (c.code === cleanVal) opt.selected = true;
  2580. grpCountries.appendChild(opt);
  2581. });
  2582. sel.appendChild(grpCountries);
  2583. }
  2584. // ==================== FIREWALL FILTER MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  2585. function switchFwRuleTab(tab) {
  2586. state.activeFwRuleTab = tab;
  2587. document.querySelectorAll('.fw-rule-tab-btn').forEach(btn => {
  2588. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  2589. btn.classList.add('text-slate-400', 'border-transparent');
  2590. });
  2591. const activeBtn = document.getElementById(`fw-tab-btn-${tab}`);
  2592. if (activeBtn) {
  2593. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  2594. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  2595. }
  2596. document.querySelectorAll('.fw-rule-pane').forEach(p => p.classList.add('hidden'));
  2597. const activePane = document.getElementById(`fw-pane-${tab}`);
  2598. if (activePane) activePane.classList.remove('hidden');
  2599. if (tab === 'statistics') {
  2600. startFwStatPolling();
  2601. } else {
  2602. stopFwStatPolling();
  2603. }
  2604. }
  2605. function toggleFwField(fieldKey, expand) {
  2606. const plusBtn = document.getElementById(`fw-plus-${fieldKey}`);
  2607. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  2608. if (!plusBtn || !fieldBox) return;
  2609. if (expand) {
  2610. plusBtn.classList.add('hidden');
  2611. fieldBox.classList.remove('hidden');
  2612. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  2613. if (valInput) valInput.focus();
  2614. } else {
  2615. fieldBox.classList.add('hidden');
  2616. plusBtn.classList.remove('hidden');
  2617. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  2618. if (valInput) {
  2619. if (valInput.tagName === 'SELECT') {
  2620. valInput.selectedIndex = 0;
  2621. } else {
  2622. valInput.value = '';
  2623. }
  2624. }
  2625. const invInput = document.getElementById(`fw-inv-${fieldKey}`);
  2626. if (invInput) invInput.checked = false;
  2627. if (fieldKey === 'cs') {
  2628. ['filter-modal-cs-established', 'filter-modal-cs-related', 'filter-modal-cs-new', 'filter-modal-cs-invalid', 'filter-modal-cs-untracked'].forEach(id => {
  2629. const el = document.getElementById(id);
  2630. if (el) el.checked = false;
  2631. });
  2632. }
  2633. if (fieldKey === 'natstate') {
  2634. ['filter-modal-nat-srcnat', 'filter-modal-nat-dstnat'].forEach(id => {
  2635. const el = document.getElementById(id);
  2636. if (el) el.checked = false;
  2637. });
  2638. }
  2639. if (fieldKey === 'days') {
  2640. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  2641. const el = document.getElementById(`fw-day-${d}`);
  2642. if (el) el.checked = true;
  2643. });
  2644. }
  2645. }
  2646. }
  2647. function setFwFieldVal(fieldKey, value, hasInvert = false) {
  2648. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  2649. toggleFwField(fieldKey, true);
  2650. let strVal = String(value);
  2651. if (hasInvert) {
  2652. const inv = strVal.startsWith('!');
  2653. if (inv) strVal = strVal.slice(1);
  2654. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  2655. if (invEl) invEl.checked = inv;
  2656. }
  2657. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  2658. if (valEl) valEl.value = strVal;
  2659. } else {
  2660. toggleFwField(fieldKey, false);
  2661. }
  2662. }
  2663. function getFwFieldVal(fieldKey, hasInvert = false) {
  2664. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  2665. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  2666. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  2667. let v = valEl ? valEl.value.trim() : '';
  2668. if (!v) return '';
  2669. if (hasInvert) {
  2670. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  2671. if (invEl && invEl.checked) {
  2672. v = '!' + v.replace(/^!/, '');
  2673. }
  2674. }
  2675. return v;
  2676. }
  2677. function toggleMaximizeFilterModal() {
  2678. const win = document.getElementById('filter-modal-window');
  2679. if (!win) return;
  2680. if (win.classList.contains('max-w-[720px]')) {
  2681. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  2682. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  2683. } else {
  2684. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  2685. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  2686. }
  2687. }
  2688. function openAddFilterModal() {
  2689. switchFwRuleTab('general');
  2690. const badge = document.getElementById('fw-modal-badge');
  2691. if (badge) badge.innerText = 'New...';
  2692. document.getElementById('filter-modal-id').value = '';
  2693. document.getElementById('filter-modal-enabled').checked = true;
  2694. document.getElementById('filter-modal-comment').value = '';
  2695. document.getElementById('filter-modal-chain').value = 'forward';
  2696. document.getElementById('filter-modal-action').value = 'accept';
  2697. document.getElementById('filter-modal-log').checked = false;
  2698. populateInterfaceSelect('fw-val-iniface');
  2699. populateInterfaceSelect('fw-val-outiface');
  2700. populateAddressListSelect('fw-val-srclist');
  2701. populateAddressListSelect('fw-val-dstlist');
  2702. populateGeoIPSelect('fw-val-srcgeo');
  2703. populateGeoIPSelect('fw-val-dstgeo');
  2704. const allFieldKeys = [
  2705. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  2706. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  2707. 'routingmark', 'conntype', 'cs', 'natstate',
  2708. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  2709. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  2710. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  2711. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  2712. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  2713. ];
  2714. allFieldKeys.forEach(k => toggleFwField(k, false));
  2715. resetCurrentRuleCounters();
  2716. toggleFilterActionFields();
  2717. document.getElementById('filter-modal').classList.remove('hidden');
  2718. }
  2719. function openEditFilterModal(id) {
  2720. const r = (state.filterRules || []).find(rule => rule.id === id);
  2721. if (!r) return;
  2722. switchFwRuleTab('general');
  2723. const badge = document.getElementById('fw-modal-badge');
  2724. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  2725. document.getElementById('filter-modal-id').value = r.id;
  2726. document.getElementById('filter-modal-enabled').checked = !r.disabled;
  2727. document.getElementById('filter-modal-comment').value = r.comment || '';
  2728. document.getElementById('filter-modal-chain').value = r.chain || 'forward';
  2729. document.getElementById('filter-modal-action').value = r.action || 'accept';
  2730. document.getElementById('filter-modal-log').checked = !!r.log;
  2731. populateInterfaceSelect('fw-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  2732. populateInterfaceSelect('fw-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  2733. populateAddressListSelect('fw-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  2734. populateAddressListSelect('fw-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  2735. populateGeoIPSelect('fw-val-srcgeo', r.src_geoip || '');
  2736. populateGeoIPSelect('fw-val-dstgeo', r.dst_geoip || '');
  2737. setFwFieldVal('src', r.src_address, true);
  2738. setFwFieldVal('dst', r.dst_address, true);
  2739. setFwFieldVal('srclist', r.src_address_list, true);
  2740. setFwFieldVal('dstlist', r.dst_address_list, true);
  2741. setFwFieldVal('srcgeo', r.src_geoip, true);
  2742. setFwFieldVal('dstgeo', r.dst_geoip, true);
  2743. if (r.protocol && r.protocol !== 'all') {
  2744. setFwFieldVal('proto', r.protocol, true);
  2745. } else {
  2746. toggleFwField('proto', false);
  2747. }
  2748. setFwFieldVal('sport', r.src_port, true);
  2749. setFwFieldVal('dport', r.dst_port, true);
  2750. setFwFieldVal('anyport', r.any_port, true);
  2751. setFwFieldVal('iniface', r.in_interface, true);
  2752. setFwFieldVal('outiface', r.out_interface, true);
  2753. setFwFieldVal('inifacelist', r.in_interface_list, true);
  2754. setFwFieldVal('outifacelist', r.out_interface_list, true);
  2755. setFwFieldVal('pktmark', r.packet_mark, true);
  2756. setFwFieldVal('connmark', r.connection_mark, true);
  2757. setFwFieldVal('routingmark', r.routing_mark, true);
  2758. setFwFieldVal('conntype', r.connection_type, false);
  2759. const states = r.connection_state || [];
  2760. if (states.length > 0) {
  2761. toggleFwField('cs', true);
  2762. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  2763. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  2764. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  2765. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  2766. document.getElementById('filter-modal-cs-untracked').checked = states.includes('untracked');
  2767. } else {
  2768. toggleFwField('cs', false);
  2769. }
  2770. const natStates = r.connection_nat_state || [];
  2771. if (natStates.length > 0) {
  2772. toggleFwField('natstate', true);
  2773. document.getElementById('filter-modal-nat-srcnat').checked = natStates.includes('srcnat');
  2774. document.getElementById('filter-modal-nat-dstnat').checked = natStates.includes('dstnat');
  2775. } else {
  2776. toggleFwField('natstate', false);
  2777. }
  2778. // Advanced tab fields
  2779. setFwFieldVal('layer7', r.layer7_protocol, false);
  2780. setFwFieldVal('content', r.content, false);
  2781. setFwFieldVal('connbytes', r.connection_bytes, false);
  2782. setFwFieldVal('connrate', r.connection_rate, false);
  2783. setFwFieldVal('pcc', r.pcc, false);
  2784. setFwFieldVal('srcmac', r.src_mac_address, true);
  2785. setFwFieldVal('outbridgeport', r.out_bridge_port, false);
  2786. setFwFieldVal('inbridgeport', r.in_bridge_port, false);
  2787. setFwFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  2788. setFwFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  2789. setFwFieldVal('ipsec', r.ipsec_policy, false);
  2790. setFwFieldVal('tlshost', r.tls_host, false);
  2791. setFwFieldVal('ingresspriority', r.ingress_priority, false);
  2792. setFwFieldVal('priority', r.priority, false);
  2793. setFwFieldVal('dscp', r.dscp, false);
  2794. setFwFieldVal('tcpmss', r.tcp_mss, false);
  2795. if (r.tos) {
  2796. const tosEl = document.getElementById('fw-val-tos');
  2797. if (tosEl) tosEl.value = r.tos;
  2798. }
  2799. setFwFieldVal('pktsize', r.packet_size, false);
  2800. setFwFieldVal('random', r.random, false);
  2801. setFwFieldVal('tcpflags', r.tcp_flags, false);
  2802. setFwFieldVal('icmpoptions', r.icmp_options, false);
  2803. setFwFieldVal('ipv4options', r.ipv4_options, false);
  2804. setFwFieldVal('ttl', r.ttl, false);
  2805. // Extra tab fields
  2806. setFwFieldVal('time', r.time, false);
  2807. if (r.days) {
  2808. toggleFwField('days', true);
  2809. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  2810. const chk = document.getElementById(`fw-day-${d}`);
  2811. if (chk) chk.checked = r.days.includes(d);
  2812. });
  2813. } else {
  2814. toggleFwField('days', false);
  2815. }
  2816. setFwFieldVal('limit', r.limit, false);
  2817. setFwFieldVal('dstlimit', r.dst_limit, false);
  2818. setFwFieldVal('psd', r.psd, false);
  2819. // Action fields
  2820. if (r.reject_with) {
  2821. const rwEl = document.getElementById('filter-modal-rejectwith');
  2822. if (rwEl) rwEl.value = r.reject_with;
  2823. }
  2824. if (r.jump_target) {
  2825. const jtEl = document.getElementById('filter-modal-jumptarget');
  2826. if (jtEl) jtEl.value = r.jump_target;
  2827. }
  2828. if (r.address_list) {
  2829. const alEl = document.getElementById('filter-modal-action-addrlist');
  2830. if (alEl) alEl.value = r.address_list;
  2831. }
  2832. if (r.address_list_timeout) {
  2833. const toEl = document.getElementById('filter-modal-action-timeout');
  2834. if (toEl) toEl.value = r.address_list_timeout;
  2835. }
  2836. setFwFieldVal('logprefix', r.log_prefix, false);
  2837. // Statistics
  2838. const bEl = document.getElementById('fw-stat-bytes');
  2839. const pEl = document.getElementById('fw-stat-packets');
  2840. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  2841. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  2842. state.fwLastBytes = r.bytes || 0;
  2843. state.fwLastPackets = r.packets || 0;
  2844. state.fwLastTimestamp = Date.now();
  2845. state.fwStatRateHistory = new Array(30).fill(0);
  2846. state.fwStatPktHistory = new Array(30).fill(0);
  2847. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  2848. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  2849. toggleFilterActionFields();
  2850. document.getElementById('filter-modal').classList.remove('hidden');
  2851. }
  2852. function closeFilterModal() {
  2853. stopFwStatPolling();
  2854. document.getElementById('filter-modal').classList.add('hidden');
  2855. }
  2856. function toggleFilterActionFields() {
  2857. const act = document.getElementById('filter-modal-action')?.value || 'accept';
  2858. const rejectBox = document.getElementById('filter-action-reject-box');
  2859. const jumpBox = document.getElementById('filter-action-jump-box');
  2860. const addrBox = document.getElementById('filter-action-addrlist-box');
  2861. if (rejectBox) {
  2862. if (act === 'reject') rejectBox.classList.remove('hidden');
  2863. else rejectBox.classList.add('hidden');
  2864. }
  2865. if (jumpBox) {
  2866. if (act === 'jump') jumpBox.classList.remove('hidden');
  2867. else jumpBox.classList.add('hidden');
  2868. }
  2869. if (addrBox) {
  2870. if (act === 'add-dst-to-address-list' || act === 'add-src-to-address-list' || act.includes('address-list') || act.includes('address list')) {
  2871. addrBox.classList.remove('hidden');
  2872. } else {
  2873. addrBox.classList.add('hidden');
  2874. }
  2875. }
  2876. if (act === 'log') {
  2877. const logEl = document.getElementById('filter-modal-log');
  2878. if (logEl) logEl.checked = true;
  2879. toggleFwField('logprefix', true);
  2880. }
  2881. }
  2882. function toggleFwLogPrefix() {
  2883. const isLog = document.getElementById('filter-modal-log')?.checked;
  2884. toggleFwField('logprefix', !!isLog);
  2885. }
  2886. function copyFilterRule() {
  2887. document.getElementById('filter-modal-id').value = '';
  2888. const badge = document.getElementById('fw-modal-badge');
  2889. if (badge) badge.innerText = 'New...';
  2890. showToast('Rule Cloned', 'Ready to save as a new rule copy', 'info');
  2891. }
  2892. function resetCurrentRuleCounters() {
  2893. state.fwStatRateHistory = new Array(30).fill(0);
  2894. state.fwStatPktHistory = new Array(30).fill(0);
  2895. state.fwLastBytes = 0;
  2896. state.fwLastPackets = 0;
  2897. state.fwLastTimestamp = Date.now();
  2898. const bEl = document.getElementById('fw-stat-bytes');
  2899. const pEl = document.getElementById('fw-stat-packets');
  2900. const rEl = document.getElementById('fw-stat-rate');
  2901. const prEl = document.getElementById('fw-stat-pktrate');
  2902. if (bEl) bEl.value = '0 B';
  2903. if (pEl) pEl.value = '0';
  2904. if (rEl) rEl.value = '0 bps';
  2905. if (prEl) prEl.value = '0 p/s';
  2906. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  2907. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  2908. showToast('Counters Reset', 'Rule counter display reset to 0', 'info');
  2909. }
  2910. async function resetAllFwCounters() {
  2911. try {
  2912. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  2913. if (res.ok) {
  2914. resetCurrentRuleCounters();
  2915. showToast('All Counters Reset', 'All firewall counters zeroed', 'success');
  2916. loadFirewall(false);
  2917. }
  2918. } catch (err) {
  2919. showToast('Error', err.message, 'error');
  2920. }
  2921. }
  2922. async function applyFilterRule(closeAfter = false) {
  2923. const id = document.getElementById('filter-modal-id').value;
  2924. const chain = document.getElementById('filter-modal-chain').value;
  2925. const action = document.getElementById('filter-modal-action').value;
  2926. const comment = document.getElementById('filter-modal-comment').value.trim();
  2927. const enabled = document.getElementById('filter-modal-enabled').checked;
  2928. const src = getFwFieldVal('src', true);
  2929. const dst = getFwFieldVal('dst', true);
  2930. const srclist = getFwFieldVal('srclist', true);
  2931. const dstlist = getFwFieldVal('dstlist', true);
  2932. const srcgeo = getFwFieldVal('srcgeo', true);
  2933. const dstgeo = getFwFieldVal('dstgeo', true);
  2934. const proto = getFwFieldVal('proto', true);
  2935. const sport = getFwFieldVal('sport', true);
  2936. const dport = getFwFieldVal('dport', true);
  2937. const anyport = getFwFieldVal('anyport', true);
  2938. const iniface = getFwFieldVal('iniface', true);
  2939. const outiface = getFwFieldVal('outiface', true);
  2940. const inifacelist = getFwFieldVal('inifacelist', true);
  2941. const outifacelist = getFwFieldVal('outifacelist', true);
  2942. const pktmark = getFwFieldVal('pktmark', true);
  2943. const connmark = getFwFieldVal('connmark', true);
  2944. const routingmark = getFwFieldVal('routingmark', true);
  2945. const conntype = getFwFieldVal('conntype', false);
  2946. const states = [];
  2947. const csBox = document.getElementById('fw-field-cs');
  2948. if (csBox && !csBox.classList.contains('hidden')) {
  2949. if (document.getElementById('filter-modal-cs-established')?.checked) states.push('established');
  2950. if (document.getElementById('filter-modal-cs-related')?.checked) states.push('related');
  2951. if (document.getElementById('filter-modal-cs-new')?.checked) states.push('new');
  2952. if (document.getElementById('filter-modal-cs-invalid')?.checked) states.push('invalid');
  2953. if (document.getElementById('filter-modal-cs-untracked')?.checked) states.push('untracked');
  2954. }
  2955. const natStates = [];
  2956. const natBox = document.getElementById('fw-field-natstate');
  2957. if (natBox && !natBox.classList.contains('hidden')) {
  2958. if (document.getElementById('filter-modal-nat-srcnat')?.checked) natStates.push('srcnat');
  2959. if (document.getElementById('filter-modal-nat-dstnat')?.checked) natStates.push('dstnat');
  2960. }
  2961. const payload = {
  2962. id,
  2963. chain,
  2964. action,
  2965. protocol: proto || 'all',
  2966. src_address: src,
  2967. dst_address: dst,
  2968. src_port: sport,
  2969. dst_port: dport,
  2970. any_port: anyport,
  2971. in_interface: iniface,
  2972. out_interface: outiface,
  2973. in_interface_list: inifacelist,
  2974. out_interface_list: outifacelist,
  2975. packet_mark: pktmark,
  2976. connection_mark: connmark,
  2977. routing_mark: routingmark,
  2978. connection_type: conntype,
  2979. connection_state: states,
  2980. connection_nat_state: natStates,
  2981. src_address_list: srclist,
  2982. dst_address_list: dstlist,
  2983. src_geoip: srcgeo,
  2984. dst_geoip: dstgeo,
  2985. comment,
  2986. disabled: !enabled,
  2987. // Advanced tab
  2988. layer7_protocol: getFwFieldVal('layer7', false),
  2989. content: getFwFieldVal('content', false),
  2990. connection_bytes: getFwFieldVal('connbytes', false),
  2991. connection_rate: getFwFieldVal('connrate', false),
  2992. pcc: getFwFieldVal('pcc', false),
  2993. src_mac_address: getFwFieldVal('srcmac', true),
  2994. out_bridge_port: getFwFieldVal('outbridgeport', false),
  2995. in_bridge_port: getFwFieldVal('inbridgeport', false),
  2996. in_bridge_port_list: getFwFieldVal('inbridgeportlist', false),
  2997. out_bridge_port_list: getFwFieldVal('outbridgeportlist', false),
  2998. ipsec_policy: getFwFieldVal('ipsec', false),
  2999. tls_host: getFwFieldVal('tlshost', false),
  3000. ingress_priority: getFwFieldVal('ingresspriority', false),
  3001. priority: getFwFieldVal('priority', false),
  3002. dscp: getFwFieldVal('dscp', false),
  3003. tcp_mss: getFwFieldVal('tcpmss', false),
  3004. tos: document.getElementById('fw-val-tos')?.value || '',
  3005. packet_size: getFwFieldVal('pktsize', false),
  3006. random: getFwFieldVal('random', false),
  3007. tcp_flags: getFwFieldVal('tcpflags', false),
  3008. icmp_options: getFwFieldVal('icmpoptions', false),
  3009. ipv4_options: getFwFieldVal('ipv4options', false),
  3010. ttl: getFwFieldVal('ttl', false),
  3011. // Extra tab
  3012. time: getFwFieldVal('time', false),
  3013. limit: getFwFieldVal('limit', false),
  3014. dst_limit: getFwFieldVal('dstlimit', false),
  3015. psd: getFwFieldVal('psd', false),
  3016. // Action tab
  3017. reject_with: action === 'reject' ? (document.getElementById('filter-modal-rejectwith')?.value || '') : '',
  3018. jump_target: action === 'jump' ? (document.getElementById('filter-modal-jumptarget')?.value || '') : '',
  3019. address_list: action.startsWith('add-') ? (document.getElementById('filter-modal-action-addrlist')?.value || '') : '',
  3020. address_list_timeout: action.startsWith('add-') ? (document.getElementById('filter-modal-action-timeout')?.value || '') : '',
  3021. log: document.getElementById('filter-modal-log')?.checked || false,
  3022. log_prefix: getFwFieldVal('logprefix', false)
  3023. };
  3024. try {
  3025. const res = await fetch(`${API_BASE}/firewall/filter`, {
  3026. method: 'POST',
  3027. headers: { 'Content-Type': 'application/json' },
  3028. body: JSON.stringify(payload)
  3029. });
  3030. if (res.ok) {
  3031. const data = await res.json();
  3032. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  3033. loadFirewall(false);
  3034. if (closeAfter) {
  3035. closeFilterModal();
  3036. } else {
  3037. if (data.id) {
  3038. document.getElementById('filter-modal-id').value = data.id;
  3039. const badge = document.getElementById('fw-modal-badge');
  3040. if (badge) badge.innerText = `#${data.id}`;
  3041. }
  3042. }
  3043. } else {
  3044. const err = await res.json();
  3045. showToast('Error', err.message || 'Failed to save rule', 'error');
  3046. }
  3047. } catch (err) {
  3048. showToast('Error', err.message, 'error');
  3049. }
  3050. }
  3051. function submitSaveFilterRule(e) {
  3052. if (e && e.preventDefault) e.preventDefault();
  3053. return applyFilterRule(true);
  3054. }
  3055. function startFwStatPolling() {
  3056. stopFwStatPolling();
  3057. pollRuleStats();
  3058. state.fwStatInterval = setInterval(pollRuleStats, 1000);
  3059. }
  3060. function stopFwStatPolling() {
  3061. if (state.fwStatInterval) {
  3062. clearInterval(state.fwStatInterval);
  3063. state.fwStatInterval = null;
  3064. }
  3065. }
  3066. async function pollRuleStats() {
  3067. const id = document.getElementById('filter-modal-id')?.value;
  3068. if (!id) {
  3069. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory || new Array(30).fill(0), 'bps', 'fw-stat-legend-rate');
  3070. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory || new Array(30).fill(0), 'p/s', 'fw-stat-legend-pktrate');
  3071. return;
  3072. }
  3073. try {
  3074. const res = await fetch(`${API_BASE}/firewall/filter`);
  3075. if (!res.ok) return;
  3076. const rules = await res.json();
  3077. const r = rules.find(x => x.id === id);
  3078. if (!r) return;
  3079. const now = Date.now();
  3080. const dt = Math.max(0.2, (now - (state.fwLastTimestamp || now)) / 1000);
  3081. state.fwLastTimestamp = now;
  3082. const curBytes = r.bytes || 0;
  3083. const curPackets = r.packets || 0;
  3084. const deltaBytes = Math.max(0, curBytes - (state.fwLastBytes || curBytes));
  3085. const deltaPkts = Math.max(0, curPackets - (state.fwLastPackets || curPackets));
  3086. state.fwLastBytes = curBytes;
  3087. state.fwLastPackets = curPackets;
  3088. const rateBps = Math.round((deltaBytes * 8) / dt);
  3089. const ratePkt = Math.round(deltaPkts / dt);
  3090. if (!state.fwStatRateHistory) state.fwStatRateHistory = new Array(30).fill(0);
  3091. if (!state.fwStatPktHistory) state.fwStatPktHistory = new Array(30).fill(0);
  3092. state.fwStatRateHistory.push(rateBps);
  3093. if (state.fwStatRateHistory.length > 30) state.fwStatRateHistory.shift();
  3094. state.fwStatPktHistory.push(ratePkt);
  3095. if (state.fwStatPktHistory.length > 30) state.fwStatPktHistory.shift();
  3096. const bEl = document.getElementById('fw-stat-bytes');
  3097. const pEl = document.getElementById('fw-stat-packets');
  3098. const rEl = document.getElementById('fw-stat-rate');
  3099. const prEl = document.getElementById('fw-stat-pktrate');
  3100. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  3101. if (pEl) pEl.value = curPackets.toLocaleString();
  3102. if (rEl) rEl.value = formatBps(rateBps);
  3103. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  3104. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3105. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3106. } catch (e) {
  3107. console.error('Error polling rule stats', e);
  3108. }
  3109. }
  3110. function formatBps(bps) {
  3111. if (bps >= 1000000000) return (bps / 1000000000).toFixed(1) + ' Gbps';
  3112. if (bps >= 1000000) return (bps / 1000000).toFixed(1) + ' Mbps';
  3113. if (bps >= 1000) return (bps / 1000).toFixed(1) + ' kbps';
  3114. return bps + ' bps';
  3115. }
  3116. function renderFwSparkline(svgId, dataArray, unit, legendId) {
  3117. const svg = document.getElementById(svgId);
  3118. if (!svg) return;
  3119. const w = 500;
  3120. const h = 100;
  3121. const paddingRight = 45;
  3122. const graphWidth = w - paddingRight;
  3123. const maxVal = Math.max(5, ...dataArray);
  3124. const currentVal = dataArray[dataArray.length - 1] || 0;
  3125. const leg = document.getElementById(legendId);
  3126. if (leg) {
  3127. leg.innerText = unit === 'bps' ? formatBps(currentVal) : `${currentVal.toLocaleString()} p/s`;
  3128. }
  3129. let gridLines = '';
  3130. for (let i = 0; i <= 5; i++) {
  3131. const y = 8 + (i * (h - 18) / 5);
  3132. const valAtLevel = Math.round(maxVal * (5 - i) / 5);
  3133. const label = unit === 'bps' ? formatBps(valAtLevel) : `${valAtLevel} p/s`;
  3134. gridLines += `
  3135. <line x1="0" y1="${y.toFixed(1)}" x2="${graphWidth}" y2="${y.toFixed(1)}" stroke="#1e2c3e" stroke-width="1" />
  3136. <text x="${w - 2}" y="${(y + 3).toFixed(1)}" fill="#64748b" font-size="9" font-family="monospace" text-anchor="end">${label}</text>
  3137. `;
  3138. }
  3139. const step = graphWidth / (dataArray.length - 1);
  3140. const points = dataArray.map((val, idx) => {
  3141. const x = idx * step;
  3142. const y = (h - 10) - (val / maxVal) * (h - 20);
  3143. return `${x.toFixed(1)},${y.toFixed(1)}`;
  3144. });
  3145. const polylineStr = points.join(' ');
  3146. const areaPath = `M 0,${h - 10} L ${polylineStr} L ${graphWidth},${h - 10} Z`;
  3147. svg.innerHTML = `
  3148. ${gridLines}
  3149. <path d="${areaPath}" fill="rgba(14, 165, 233, 0.12)" />
  3150. <polyline fill="none" stroke="#38bdf8" stroke-width="1.8" stroke-linejoin="round" points="${polylineStr}" />
  3151. <circle cx="${graphWidth}" cy="${points[points.length - 1].split(',')[1]}" r="3" fill="#38bdf8" />
  3152. `;
  3153. }
  3154. async function moveFilterRule(id, dir) {
  3155. try {
  3156. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  3157. method: 'POST',
  3158. headers: { 'Content-Type': 'application/json' },
  3159. body: JSON.stringify({ direction: dir })
  3160. });
  3161. if (res.ok) loadFirewall(false);
  3162. } catch (err) {
  3163. showToast('Error', err.message, 'error');
  3164. }
  3165. }
  3166. async function toggleFilterRuleState(id, disabled) {
  3167. try {
  3168. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  3169. method: 'POST',
  3170. headers: { 'Content-Type': 'application/json' },
  3171. body: JSON.stringify({ disabled })
  3172. });
  3173. if (res.ok) loadFirewall(false);
  3174. } catch (err) {
  3175. showToast('Error', err.message, 'error');
  3176. }
  3177. }
  3178. async function deleteFilterRule(id) {
  3179. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  3180. try {
  3181. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3182. if (res.ok) {
  3183. showToast('Deleted', 'Filter rule removed', 'success');
  3184. loadFirewall(false);
  3185. }
  3186. } catch (err) {
  3187. showToast('Error', err.message, 'error');
  3188. }
  3189. }
  3190. // ----------------- NAT Rules -----------------
  3191. function renderNATRules() {
  3192. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  3193. const tbody = document.getElementById('nat-table-body');
  3194. const empty = document.getElementById('nat-empty');
  3195. if (!tbody) return;
  3196. tbody.innerHTML = '';
  3197. const rules = (state.natRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  3198. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  3199. if (rules.length === 0) {
  3200. empty?.classList.remove('hidden');
  3201. return;
  3202. }
  3203. empty?.classList.add('hidden');
  3204. rules.forEach((r, idx) => {
  3205. const tr = document.createElement('tr');
  3206. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  3207. let toTarget = '-';
  3208. if (r.action === 'jump') {
  3209. toTarget = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  3210. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  3211. toTarget = `<span class="text-emerald-300 font-mono font-bold">&rarr; ${r.address_list || '-'}</span>`;
  3212. } else if (r.action === 'redirect') {
  3213. toTarget = `<span class="text-amber-300 font-mono font-bold">ports:${r.to_ports || 'all'}</span>`;
  3214. } else if (r.action === 'masquerade') {
  3215. toTarget = r.to_ports ? `<span class="text-amber-300 font-mono font-bold">ports:${r.to_ports}</span>` : `<span class="text-slate-500 font-mono">-</span>`;
  3216. } else if (r.action === 'log') {
  3217. toTarget = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  3218. } else {
  3219. const parts = [r.to_addresses, r.to_ports].filter(Boolean);
  3220. toTarget = parts.length ? `<span class="text-amber-300 font-mono font-bold">${parts.join(':')}</span>` : '-';
  3221. }
  3222. const ifaces = [r.out_interface ? 'out:' + r.out_interface : '', r.in_interface ? 'in:' + r.in_interface : ''].filter(Boolean).join(' ');
  3223. tr.innerHTML = `
  3224. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  3225. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  3226. <td class="py-2.5 px-3 font-bold text-amber-400">${r.chain}</td>
  3227. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  3228. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  3229. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}${r.dst_port ? ':' + r.dst_port : ''}</td>
  3230. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  3231. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  3232. <td class="py-2.5 px-3 font-mono text-xs">${toTarget}</td>
  3233. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  3234. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  3235. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  3236. </td>
  3237. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  3238. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3239. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  3240. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  3241. <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>
  3242. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3243. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3244. </td>
  3245. `;
  3246. tbody.appendChild(tr);
  3247. });
  3248. }
  3249. // ==================== FIREWALL NAT MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  3250. function switchNATRuleTab(tab) {
  3251. state.activeNATRuleTab = tab;
  3252. document.querySelectorAll('.nat-rule-tab-btn').forEach(btn => {
  3253. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  3254. btn.classList.add('text-slate-400', 'border-transparent');
  3255. });
  3256. const activeBtn = document.getElementById(`nat-tab-btn-${tab}`);
  3257. if (activeBtn) {
  3258. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  3259. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  3260. }
  3261. document.querySelectorAll('.nat-rule-pane').forEach(p => p.classList.add('hidden'));
  3262. const activePane = document.getElementById(`nat-pane-${tab}`);
  3263. if (activePane) activePane.classList.remove('hidden');
  3264. if (tab === 'statistics') {
  3265. startNATStatPolling();
  3266. } else {
  3267. stopNATStatPolling();
  3268. }
  3269. }
  3270. function toggleNATField(fieldKey, expand) {
  3271. const plusBtn = document.getElementById(`nat-plus-${fieldKey}`);
  3272. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  3273. if (!plusBtn || !fieldBox) return;
  3274. if (expand) {
  3275. plusBtn.classList.add('hidden');
  3276. fieldBox.classList.remove('hidden');
  3277. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  3278. if (valInput) valInput.focus();
  3279. } else {
  3280. fieldBox.classList.add('hidden');
  3281. plusBtn.classList.remove('hidden');
  3282. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  3283. if (valInput) {
  3284. if (valInput.tagName === 'SELECT') {
  3285. valInput.selectedIndex = 0;
  3286. } else {
  3287. valInput.value = '';
  3288. }
  3289. }
  3290. const invInput = document.getElementById(`nat-inv-${fieldKey}`);
  3291. if (invInput) invInput.checked = false;
  3292. if (fieldKey === 'days') {
  3293. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3294. const el = document.getElementById(`nat-day-${d}`);
  3295. if (el) el.checked = true;
  3296. });
  3297. }
  3298. }
  3299. }
  3300. function setNATFieldVal(fieldKey, value, hasInvert = false) {
  3301. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  3302. toggleNATField(fieldKey, true);
  3303. let strVal = String(value);
  3304. if (hasInvert) {
  3305. const inv = strVal.startsWith('!');
  3306. if (inv) strVal = strVal.slice(1);
  3307. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  3308. if (invEl) invEl.checked = inv;
  3309. }
  3310. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  3311. if (valEl) valEl.value = strVal;
  3312. } else {
  3313. toggleNATField(fieldKey, false);
  3314. }
  3315. }
  3316. function getNATFieldVal(fieldKey, hasInvert = false) {
  3317. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  3318. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3319. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  3320. let v = valEl ? valEl.value.trim() : '';
  3321. if (!v) return '';
  3322. if (hasInvert) {
  3323. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  3324. if (invEl && invEl.checked) {
  3325. v = '!' + v.replace(/^!/, '');
  3326. }
  3327. }
  3328. return v;
  3329. }
  3330. function toggleMaximizeNATModal() {
  3331. const win = document.getElementById('nat-modal-window');
  3332. if (!win) return;
  3333. if (win.classList.contains('max-w-[720px]')) {
  3334. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3335. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3336. } else {
  3337. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3338. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3339. }
  3340. }
  3341. function handleNATChainChange() {
  3342. const ch = document.getElementById('nat-modal-chain')?.value || 'srcnat';
  3343. const actSel = document.getElementById('nat-modal-action');
  3344. if (actSel) {
  3345. if (ch === 'srcnat' && (actSel.value === 'dst-nat' || actSel.value === 'redirect')) {
  3346. actSel.value = 'masquerade';
  3347. } else if (ch === 'dstnat' && (actSel.value === 'masquerade' || actSel.value === 'src-nat')) {
  3348. actSel.value = 'dst-nat';
  3349. }
  3350. }
  3351. toggleNATActionFields();
  3352. }
  3353. function toggleNATActionFields() {
  3354. const act = document.getElementById('nat-modal-action')?.value || 'masquerade';
  3355. const rowAddr = document.getElementById('nat-row-toaddr');
  3356. const rowPort = document.getElementById('nat-row-toport');
  3357. const jumpBox = document.getElementById('nat-action-jump-box');
  3358. const addrBox = document.getElementById('nat-action-addrlist-box');
  3359. // Hide all dynamic rows first
  3360. if (rowAddr) rowAddr.classList.add('hidden');
  3361. if (rowPort) rowPort.classList.add('hidden');
  3362. if (jumpBox) jumpBox.classList.add('hidden');
  3363. if (addrBox) addrBox.classList.add('hidden');
  3364. if (['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(act)) {
  3365. if (rowAddr) rowAddr.classList.remove('hidden');
  3366. if (rowPort) rowPort.classList.remove('hidden');
  3367. } else if (act === 'redirect' || act === 'masquerade') {
  3368. if (rowPort) rowPort.classList.remove('hidden');
  3369. } else if (act === 'jump') {
  3370. if (jumpBox) jumpBox.classList.remove('hidden');
  3371. } else if (act.includes('address-list') || act.includes('address list')) {
  3372. if (addrBox) addrBox.classList.remove('hidden');
  3373. }
  3374. if (act === 'log') {
  3375. const logEl = document.getElementById('nat-modal-log');
  3376. if (logEl) logEl.checked = true;
  3377. toggleNATField('logprefix', true);
  3378. }
  3379. }
  3380. function toggleNATLogPrefix() {
  3381. const isLog = document.getElementById('nat-modal-log')?.checked;
  3382. toggleNATField('logprefix', !!isLog);
  3383. }
  3384. function openAddNATModal() {
  3385. switchNATRuleTab('general');
  3386. const badge = document.getElementById('nat-modal-badge');
  3387. if (badge) badge.innerText = 'New...';
  3388. document.getElementById('nat-modal-id').value = '';
  3389. document.getElementById('nat-modal-enabled').checked = true;
  3390. document.getElementById('nat-modal-comment').value = '';
  3391. document.getElementById('nat-modal-chain').value = 'srcnat';
  3392. document.getElementById('nat-modal-action').value = 'masquerade';
  3393. document.getElementById('nat-modal-toaddr').value = '';
  3394. document.getElementById('nat-modal-toport').value = '';
  3395. document.getElementById('nat-modal-log').checked = false;
  3396. populateInterfaceSelect('nat-val-iniface');
  3397. populateInterfaceSelect('nat-val-outiface');
  3398. populateAddressListSelect('nat-val-srclist');
  3399. populateAddressListSelect('nat-val-dstlist');
  3400. populateGeoIPSelect('nat-val-srcgeo');
  3401. populateGeoIPSelect('nat-val-dstgeo');
  3402. const allFieldKeys = [
  3403. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  3404. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  3405. 'routingmark', 'conntype',
  3406. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  3407. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  3408. 'ipsec', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  3409. 'pktsize', 'random', 'icmpoptions', 'ipv4options', 'ttl',
  3410. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  3411. ];
  3412. allFieldKeys.forEach(k => toggleNATField(k, false));
  3413. resetCurrentNATRuleCounters();
  3414. toggleNATActionFields();
  3415. document.getElementById('nat-modal').classList.remove('hidden');
  3416. }
  3417. function openEditNATModal(id) {
  3418. const r = (state.natRules || []).find(rule => rule.id === id);
  3419. if (!r) return;
  3420. switchNATRuleTab('general');
  3421. const badge = document.getElementById('nat-modal-badge');
  3422. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  3423. document.getElementById('nat-modal-id').value = r.id;
  3424. document.getElementById('nat-modal-enabled').checked = !r.disabled;
  3425. document.getElementById('nat-modal-comment').value = r.comment || '';
  3426. document.getElementById('nat-modal-chain').value = r.chain || 'srcnat';
  3427. document.getElementById('nat-modal-action').value = r.action || 'masquerade';
  3428. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  3429. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  3430. document.getElementById('nat-modal-log').checked = !!r.log;
  3431. populateInterfaceSelect('nat-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  3432. populateInterfaceSelect('nat-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  3433. populateAddressListSelect('nat-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  3434. populateAddressListSelect('nat-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  3435. populateGeoIPSelect('nat-val-srcgeo', r.src_geoip || '');
  3436. populateGeoIPSelect('nat-val-dstgeo', r.dst_geoip || '');
  3437. setNATFieldVal('src', r.src_address, true);
  3438. setNATFieldVal('dst', r.dst_address, true);
  3439. setNATFieldVal('srclist', r.src_address_list, true);
  3440. setNATFieldVal('dstlist', r.dst_address_list, true);
  3441. setNATFieldVal('srcgeo', r.src_geoip, true);
  3442. setNATFieldVal('dstgeo', r.dst_geoip, true);
  3443. if (r.protocol && r.protocol !== 'all') {
  3444. setNATFieldVal('proto', r.protocol, true);
  3445. } else {
  3446. toggleNATField('proto', false);
  3447. }
  3448. setNATFieldVal('sport', r.src_port, true);
  3449. setNATFieldVal('dport', r.dst_port, true);
  3450. setNATFieldVal('anyport', r.any_port, true);
  3451. setNATFieldVal('iniface', r.in_interface, true);
  3452. setNATFieldVal('outiface', r.out_interface, true);
  3453. setNATFieldVal('inifacelist', r.in_interface_list, true);
  3454. setNATFieldVal('outifacelist', r.out_interface_list, true);
  3455. setNATFieldVal('pktmark', r.packet_mark, true);
  3456. setNATFieldVal('connmark', r.connection_mark, true);
  3457. setNATFieldVal('routingmark', r.routing_mark, true);
  3458. setNATFieldVal('conntype', r.connection_type, false);
  3459. // Advanced tab fields
  3460. setNATFieldVal('layer7', r.layer7_protocol, false);
  3461. setNATFieldVal('content', r.content, false);
  3462. setNATFieldVal('connbytes', r.connection_bytes, false);
  3463. setNATFieldVal('connrate', r.connection_rate, false);
  3464. setNATFieldVal('pcc', r.pcc, false);
  3465. setNATFieldVal('srcmac', r.src_mac_address, true);
  3466. setNATFieldVal('outbridgeport', r.out_bridge_port, false);
  3467. setNATFieldVal('inbridgeport', r.in_bridge_port, false);
  3468. setNATFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  3469. setNATFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  3470. setNATFieldVal('ipsec', r.ipsec_policy, false);
  3471. setNATFieldVal('ingresspriority', r.ingress_priority, false);
  3472. setNATFieldVal('priority', r.priority, false);
  3473. setNATFieldVal('dscp', r.dscp, false);
  3474. setNATFieldVal('tcpmss', r.tcp_mss, false);
  3475. if (r.tos) {
  3476. const tosEl = document.getElementById('nat-val-tos');
  3477. if (tosEl) tosEl.value = r.tos;
  3478. }
  3479. setNATFieldVal('pktsize', r.packet_size, false);
  3480. setNATFieldVal('random', r.random, false);
  3481. setNATFieldVal('icmpoptions', r.icmp_options, false);
  3482. setNATFieldVal('ipv4options', r.ipv4_options, false);
  3483. setNATFieldVal('ttl', r.ttl, false);
  3484. // Extra tab fields
  3485. setNATFieldVal('time', r.time, false);
  3486. if (r.days) {
  3487. toggleNATField('days', true);
  3488. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3489. const chk = document.getElementById(`nat-day-${d}`);
  3490. if (chk) chk.checked = r.days.includes(d);
  3491. });
  3492. } else {
  3493. toggleNATField('days', false);
  3494. }
  3495. setNATFieldVal('limit', r.limit, false);
  3496. setNATFieldVal('dstlimit', r.dst_limit, false);
  3497. setNATFieldVal('psd', r.psd, false);
  3498. // Action fields
  3499. if (r.jump_target) {
  3500. const jtEl = document.getElementById('nat-modal-jumptarget');
  3501. if (jtEl) jtEl.value = r.jump_target;
  3502. }
  3503. if (r.address_list) {
  3504. const alEl = document.getElementById('nat-modal-action-addrlist');
  3505. if (alEl) alEl.value = r.address_list;
  3506. }
  3507. if (r.address_list_timeout) {
  3508. const toEl = document.getElementById('nat-modal-action-timeout');
  3509. if (toEl) toEl.value = r.address_list_timeout;
  3510. }
  3511. setNATFieldVal('logprefix', r.log_prefix, false);
  3512. // Statistics
  3513. const bEl = document.getElementById('nat-stat-bytes');
  3514. const pEl = document.getElementById('nat-stat-packets');
  3515. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  3516. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  3517. state.natLastBytes = r.bytes || 0;
  3518. state.natLastPackets = r.packets || 0;
  3519. state.natLastTimestamp = Date.now();
  3520. state.natStatRateHistory = new Array(30).fill(0);
  3521. state.natStatPktHistory = new Array(30).fill(0);
  3522. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  3523. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  3524. toggleNATActionFields();
  3525. document.getElementById('nat-modal').classList.remove('hidden');
  3526. }
  3527. function closeNATModal() {
  3528. stopNATStatPolling();
  3529. document.getElementById('nat-modal').classList.add('hidden');
  3530. }
  3531. function copyNATRule() {
  3532. document.getElementById('nat-modal-id').value = '';
  3533. const badge = document.getElementById('nat-modal-badge');
  3534. if (badge) badge.innerText = 'New...';
  3535. showToast('Rule Cloned', 'Ready to save as a new NAT rule copy', 'info');
  3536. }
  3537. function resetCurrentNATRuleCounters() {
  3538. state.natStatRateHistory = new Array(30).fill(0);
  3539. state.natStatPktHistory = new Array(30).fill(0);
  3540. state.natLastBytes = 0;
  3541. state.natLastPackets = 0;
  3542. state.natLastTimestamp = Date.now();
  3543. const bEl = document.getElementById('nat-stat-bytes');
  3544. const pEl = document.getElementById('nat-stat-packets');
  3545. const rEl = document.getElementById('nat-stat-rate');
  3546. const prEl = document.getElementById('nat-stat-pktrate');
  3547. if (bEl) bEl.value = '0 B';
  3548. if (pEl) pEl.value = '0';
  3549. if (rEl) rEl.value = '0 bps';
  3550. if (prEl) prEl.value = '0 p/s';
  3551. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  3552. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  3553. showToast('Counters Reset', 'NAT rule counter display reset to 0', 'info');
  3554. }
  3555. async function applyNATRule(closeAfter = false) {
  3556. const id = document.getElementById('nat-modal-id').value;
  3557. const chain = document.getElementById('nat-modal-chain').value;
  3558. const action = document.getElementById('nat-modal-action').value;
  3559. const comment = document.getElementById('nat-modal-comment').value.trim();
  3560. const enabled = document.getElementById('nat-modal-enabled').checked;
  3561. const src = getNATFieldVal('src', true);
  3562. const dst = getNATFieldVal('dst', true);
  3563. const srclist = getNATFieldVal('srclist', true);
  3564. const dstlist = getNATFieldVal('dstlist', true);
  3565. const srcgeo = getNATFieldVal('srcgeo', true);
  3566. const dstgeo = getNATFieldVal('dstgeo', true);
  3567. const proto = getNATFieldVal('proto', true);
  3568. const sport = getNATFieldVal('sport', true);
  3569. const dport = getNATFieldVal('dport', true);
  3570. const anyport = getNATFieldVal('anyport', true);
  3571. const iniface = getNATFieldVal('iniface', true);
  3572. const outiface = getNATFieldVal('outiface', true);
  3573. const inifacelist = getNATFieldVal('inifacelist', true);
  3574. const outifacelist = getNATFieldVal('outifacelist', true);
  3575. const pktmark = getNATFieldVal('pktmark', true);
  3576. const connmark = getNATFieldVal('connmark', true);
  3577. const routingmark = getNATFieldVal('routingmark', true);
  3578. const conntype = getNATFieldVal('conntype', false);
  3579. const usesAddr = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(action);
  3580. const usesPort = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat', 'redirect', 'masquerade'].includes(action);
  3581. const payload = {
  3582. id,
  3583. chain,
  3584. action,
  3585. to_addresses: usesAddr ? (document.getElementById('nat-modal-toaddr')?.value.trim() || '') : '',
  3586. to_ports: usesPort ? (document.getElementById('nat-modal-toport')?.value.trim() || '') : '',
  3587. protocol: proto || 'all',
  3588. src_address: src,
  3589. dst_address: dst,
  3590. src_port: sport,
  3591. dst_port: dport,
  3592. any_port: anyport,
  3593. in_interface: iniface,
  3594. out_interface: outiface,
  3595. in_interface_list: inifacelist,
  3596. out_interface_list: outifacelist,
  3597. packet_mark: pktmark,
  3598. connection_mark: connmark,
  3599. routing_mark: routingmark,
  3600. connection_type: conntype,
  3601. src_address_list: srclist,
  3602. dst_address_list: dstlist,
  3603. src_geoip: srcgeo,
  3604. dst_geoip: dstgeo,
  3605. comment,
  3606. disabled: !enabled,
  3607. // Advanced tab
  3608. layer7_protocol: getNATFieldVal('layer7', false),
  3609. content: getNATFieldVal('content', false),
  3610. connection_bytes: getNATFieldVal('connbytes', false),
  3611. connection_rate: getNATFieldVal('connrate', false),
  3612. pcc: getNATFieldVal('pcc', false),
  3613. src_mac_address: getNATFieldVal('srcmac', true),
  3614. out_bridge_port: getNATFieldVal('outbridgeport', false),
  3615. in_bridge_port: getNATFieldVal('inbridgeport', false),
  3616. in_bridge_port_list: getNATFieldVal('inbridgeportlist', false),
  3617. out_bridge_port_list: getNATFieldVal('outbridgeportlist', false),
  3618. ipsec_policy: getNATFieldVal('ipsec', false),
  3619. ingress_priority: getNATFieldVal('ingresspriority', false),
  3620. priority: getNATFieldVal('priority', false),
  3621. dscp: getNATFieldVal('dscp', false),
  3622. tcp_mss: getNATFieldVal('tcpmss', false),
  3623. tos: document.getElementById('nat-val-tos')?.value || '',
  3624. packet_size: getNATFieldVal('pktsize', false),
  3625. random: getNATFieldVal('random', false),
  3626. icmp_options: getNATFieldVal('icmpoptions', false),
  3627. ipv4_options: getNATFieldVal('ipv4options', false),
  3628. ttl: getNATFieldVal('ttl', false),
  3629. // Extra tab
  3630. time: getNATFieldVal('time', false),
  3631. limit: getNATFieldVal('limit', false),
  3632. dst_limit: getNATFieldVal('dstlimit', false),
  3633. psd: getNATFieldVal('psd', false),
  3634. // Action tab
  3635. jump_target: action === 'jump' ? (document.getElementById('nat-modal-jumptarget')?.value || '') : '',
  3636. address_list: action.includes('address') ? (document.getElementById('nat-modal-action-addrlist')?.value || '') : '',
  3637. address_list_timeout: action.includes('address') ? (document.getElementById('nat-modal-action-timeout')?.value || '') : '',
  3638. log: document.getElementById('nat-modal-log')?.checked || false,
  3639. log_prefix: getNATFieldVal('logprefix', false)
  3640. };
  3641. try {
  3642. const res = await fetch(`${API_BASE}/firewall/nat`, {
  3643. method: 'POST',
  3644. headers: { 'Content-Type': 'application/json' },
  3645. body: JSON.stringify(payload)
  3646. });
  3647. if (res.ok) {
  3648. const data = await res.json();
  3649. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  3650. loadFirewall(false);
  3651. if (closeAfter) {
  3652. closeNATModal();
  3653. } else {
  3654. if (data.id) {
  3655. document.getElementById('nat-modal-id').value = data.id;
  3656. const badge = document.getElementById('nat-modal-badge');
  3657. if (badge) badge.innerText = `#${data.id}`;
  3658. }
  3659. }
  3660. } else {
  3661. const err = await res.json();
  3662. showToast('Error', err.message || 'Failed to save rule', 'error');
  3663. }
  3664. } catch (err) {
  3665. showToast('Error', err.message, 'error');
  3666. }
  3667. }
  3668. function submitSaveNATRule(e) {
  3669. if (e && e.preventDefault) e.preventDefault();
  3670. return applyNATRule(true);
  3671. }
  3672. function startNATStatPolling() {
  3673. stopNATStatPolling();
  3674. pollNATRuleStats();
  3675. state.natStatInterval = setInterval(pollNATRuleStats, 1000);
  3676. }
  3677. function stopNATStatPolling() {
  3678. if (state.natStatInterval) {
  3679. clearInterval(state.natStatInterval);
  3680. state.natStatInterval = null;
  3681. }
  3682. }
  3683. async function pollNATRuleStats() {
  3684. const id = document.getElementById('nat-modal-id')?.value;
  3685. if (!id) {
  3686. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory || new Array(30).fill(0), 'bps', 'nat-stat-legend-rate');
  3687. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory || new Array(30).fill(0), 'p/s', 'nat-stat-legend-pktrate');
  3688. return;
  3689. }
  3690. try {
  3691. const res = await fetch(`${API_BASE}/firewall/nat`);
  3692. if (!res.ok) return;
  3693. const rules = await res.json();
  3694. const r = rules.find(x => x.id === id);
  3695. if (!r) return;
  3696. const now = Date.now();
  3697. const dt = Math.max(0.2, (now - (state.natLastTimestamp || now)) / 1000);
  3698. state.natLastTimestamp = now;
  3699. const curBytes = r.bytes || 0;
  3700. const curPackets = r.packets || 0;
  3701. const deltaBytes = Math.max(0, curBytes - (state.natLastBytes || curBytes));
  3702. const deltaPkts = Math.max(0, curPackets - (state.natLastPackets || curPackets));
  3703. state.natLastBytes = curBytes;
  3704. state.natLastPackets = curPackets;
  3705. const rateBps = Math.round((deltaBytes * 8) / dt);
  3706. const ratePkt = Math.round(deltaPkts / dt);
  3707. if (!state.natStatRateHistory) state.natStatRateHistory = new Array(30).fill(0);
  3708. if (!state.natStatPktHistory) state.natStatPktHistory = new Array(30).fill(0);
  3709. state.natStatRateHistory.push(rateBps);
  3710. if (state.natStatRateHistory.length > 30) state.natStatRateHistory.shift();
  3711. state.natStatPktHistory.push(ratePkt);
  3712. if (state.natStatPktHistory.length > 30) state.natStatPktHistory.shift();
  3713. const bEl = document.getElementById('nat-stat-bytes');
  3714. const pEl = document.getElementById('nat-stat-packets');
  3715. const rEl = document.getElementById('nat-stat-rate');
  3716. const prEl = document.getElementById('nat-stat-pktrate');
  3717. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  3718. if (pEl) pEl.value = curPackets.toLocaleString();
  3719. if (rEl) rEl.value = formatBps(rateBps);
  3720. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  3721. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  3722. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  3723. } catch (e) {
  3724. console.error('Error polling NAT rule stats', e);
  3725. }
  3726. }
  3727. async function moveNATRule(id, dir) {
  3728. try {
  3729. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  3730. method: 'POST',
  3731. headers: { 'Content-Type': 'application/json' },
  3732. body: JSON.stringify({ direction: dir })
  3733. });
  3734. if (res.ok) loadFirewall(false);
  3735. } catch (err) {
  3736. showToast('Error', err.message, 'error');
  3737. }
  3738. }
  3739. async function toggleNATRuleState(id, disabled) {
  3740. try {
  3741. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  3742. method: 'POST',
  3743. headers: { 'Content-Type': 'application/json' },
  3744. body: JSON.stringify({ disabled })
  3745. });
  3746. if (res.ok) loadFirewall(false);
  3747. } catch (err) {
  3748. showToast('Error', err.message, 'error');
  3749. }
  3750. }
  3751. async function deleteNATRule(id) {
  3752. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  3753. try {
  3754. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3755. if (res.ok) {
  3756. showToast('Deleted', 'NAT rule removed', 'success');
  3757. loadFirewall(false);
  3758. }
  3759. } catch (err) {
  3760. showToast('Error', err.message, 'error');
  3761. }
  3762. }
  3763. // ----------------- Mangle Rules -----------------
  3764. function renderMangleRules() {
  3765. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  3766. const tbody = document.getElementById('mangle-table-body');
  3767. const empty = document.getElementById('mangle-empty');
  3768. if (!tbody) return;
  3769. tbody.innerHTML = '';
  3770. const rules = (state.mangleRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  3771. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  3772. if (rules.length === 0) {
  3773. empty?.classList.remove('hidden');
  3774. return;
  3775. }
  3776. empty?.classList.add('hidden');
  3777. rules.forEach((r, idx) => {
  3778. const tr = document.createElement('tr');
  3779. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  3780. let markVal = '<span class="text-slate-500">-</span>';
  3781. if (r.new_connection_mark) markVal = `<span class="text-cyan-300 font-mono font-bold">${r.new_connection_mark}</span>`;
  3782. else if (r.new_routing_mark) markVal = `<span class="text-amber-300 font-mono font-bold">${r.new_routing_mark}</span>`;
  3783. else if (r.new_packet_mark) markVal = `<span class="text-emerald-300 font-mono font-bold">${r.new_packet_mark}</span>`;
  3784. else if (r.new_mss) markVal = `<span class="text-sky-300 font-mono font-bold">mss:${r.new_mss}</span>`;
  3785. else if (r.new_dscp) markVal = `<span class="text-purple-300 font-mono font-bold">dscp:${r.new_dscp}</span>`;
  3786. else if (r.new_ttl) markVal = `<span class="text-blue-300 font-mono font-bold">ttl:${r.new_ttl}</span>`;
  3787. else if (r.new_priority) markVal = `<span class="text-indigo-300 font-mono font-bold">prio:${r.new_priority}</span>`;
  3788. else if (r.route) markVal = `<span class="text-orange-300 font-mono font-bold">route:${r.route}</span>`;
  3789. else if (r.sniff_target) markVal = `<span class="text-pink-300 font-mono font-bold">sniff:${r.sniff_target}</span>`;
  3790. else if (r.action === 'jump') markVal = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  3791. else if (r.action.includes('address-list') || r.action.includes('address list')) markVal = `<span class="text-emerald-300 font-mono font-bold">&rarr; ${r.address_list || '-'}</span>`;
  3792. else if (r.action === 'log') markVal = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  3793. tr.innerHTML = `
  3794. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  3795. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  3796. <td class="py-2.5 px-3 font-bold text-purple-400">${r.chain}</td>
  3797. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  3798. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  3799. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  3800. <td class="py-2.5 px-3 font-mono text-xs">${markVal}</td>
  3801. <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>
  3802. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  3803. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  3804. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  3805. </td>
  3806. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  3807. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3808. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  3809. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  3810. <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>
  3811. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3812. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3813. </td>
  3814. `;
  3815. tbody.appendChild(tr);
  3816. });
  3817. }
  3818. // ==================== FIREWALL MANGLE MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  3819. function switchMangleRuleTab(tab) {
  3820. state.activeMangleRuleTab = tab;
  3821. document.querySelectorAll('.mangle-rule-tab-btn').forEach(btn => {
  3822. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  3823. btn.classList.add('text-slate-400', 'border-transparent');
  3824. });
  3825. const activeBtn = document.getElementById(`mangle-tab-btn-${tab}`);
  3826. if (activeBtn) {
  3827. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  3828. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  3829. }
  3830. document.querySelectorAll('.mangle-rule-pane').forEach(p => p.classList.add('hidden'));
  3831. const activePane = document.getElementById(`mangle-pane-${tab}`);
  3832. if (activePane) activePane.classList.remove('hidden');
  3833. if (tab === 'statistics') {
  3834. startMangleStatPolling();
  3835. } else {
  3836. stopMangleStatPolling();
  3837. }
  3838. }
  3839. function toggleMangleField(fieldKey, expand) {
  3840. const plusBtn = document.getElementById(`mangle-plus-${fieldKey}`);
  3841. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  3842. if (!plusBtn || !fieldBox) return;
  3843. if (expand) {
  3844. plusBtn.classList.add('hidden');
  3845. fieldBox.classList.remove('hidden');
  3846. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  3847. if (valInput) valInput.focus();
  3848. } else {
  3849. fieldBox.classList.add('hidden');
  3850. plusBtn.classList.remove('hidden');
  3851. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  3852. if (valInput) {
  3853. if (valInput.tagName === 'SELECT') {
  3854. valInput.selectedIndex = 0;
  3855. } else {
  3856. valInput.value = '';
  3857. }
  3858. }
  3859. const invInput = document.getElementById(`mangle-inv-${fieldKey}`);
  3860. if (invInput) invInput.checked = false;
  3861. if (fieldKey === 'cs') {
  3862. ['mangle-modal-cs-established', 'mangle-modal-cs-related', 'mangle-modal-cs-new', 'mangle-modal-cs-invalid', 'mangle-modal-cs-untracked'].forEach(id => {
  3863. const el = document.getElementById(id);
  3864. if (el) el.checked = false;
  3865. });
  3866. }
  3867. if (fieldKey === 'natstate') {
  3868. ['mangle-modal-nat-srcnat', 'mangle-modal-nat-dstnat'].forEach(id => {
  3869. const el = document.getElementById(id);
  3870. if (el) el.checked = false;
  3871. });
  3872. }
  3873. }
  3874. }
  3875. function setMangleFieldVal(fieldKey, value, hasInvert = false) {
  3876. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  3877. toggleMangleField(fieldKey, true);
  3878. let strVal = String(value);
  3879. if (hasInvert) {
  3880. const inv = strVal.startsWith('!');
  3881. if (inv) strVal = strVal.slice(1);
  3882. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  3883. if (invEl) invEl.checked = inv;
  3884. }
  3885. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  3886. if (valEl) valEl.value = strVal;
  3887. } else {
  3888. toggleMangleField(fieldKey, false);
  3889. }
  3890. }
  3891. function getMangleFieldVal(fieldKey, hasInvert = false) {
  3892. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  3893. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3894. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  3895. let v = valEl ? valEl.value.trim() : '';
  3896. if (!v) return '';
  3897. if (hasInvert) {
  3898. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  3899. if (invEl && invEl.checked) {
  3900. v = '!' + v.replace(/^!/, '');
  3901. }
  3902. }
  3903. return v;
  3904. }
  3905. function toggleMaximizeMangleModal() {
  3906. const win = document.getElementById('mangle-modal-window');
  3907. if (!win) return;
  3908. if (win.classList.contains('max-w-[720px]')) {
  3909. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3910. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3911. } else {
  3912. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3913. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3914. }
  3915. }
  3916. function toggleMangleActionFields() {
  3917. const act = document.getElementById('mangle-modal-action')?.value || 'mark-connection';
  3918. // Hide all dynamic rows first
  3919. ['newconnmark', 'newroutingmark', 'newpktmark', 'newmss', 'newdscp', 'newttl', 'newpriority', 'route', 'sniff', 'passthrough'].forEach(id => {
  3920. const el = document.getElementById(`mangle-row-${id}`);
  3921. if (el) el.classList.add('hidden');
  3922. });
  3923. const jumpBox = document.getElementById('mangle-action-jump-box');
  3924. const addrBox = document.getElementById('mangle-action-addrlist-box');
  3925. if (jumpBox) jumpBox.classList.add('hidden');
  3926. if (addrBox) addrBox.classList.add('hidden');
  3927. // Activate matching rows
  3928. if (act === 'mark-connection') {
  3929. document.getElementById('mangle-row-newconnmark')?.classList.remove('hidden');
  3930. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  3931. } else if (act === 'mark-routing') {
  3932. document.getElementById('mangle-row-newroutingmark')?.classList.remove('hidden');
  3933. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  3934. } else if (act === 'mark-packet') {
  3935. document.getElementById('mangle-row-newpktmark')?.classList.remove('hidden');
  3936. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  3937. } else if (act === 'change-mss') {
  3938. document.getElementById('mangle-row-newmss')?.classList.remove('hidden');
  3939. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  3940. } else if (act === 'change-dscp') {
  3941. document.getElementById('mangle-row-newdscp')?.classList.remove('hidden');
  3942. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  3943. } else if (act === 'change-ttl') {
  3944. document.getElementById('mangle-row-newttl')?.classList.remove('hidden');
  3945. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  3946. } else if (act === 'set-priority') {
  3947. document.getElementById('mangle-row-newpriority')?.classList.remove('hidden');
  3948. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  3949. } else if (act === 'route') {
  3950. document.getElementById('mangle-row-route')?.classList.remove('hidden');
  3951. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  3952. } else if (act === 'sniff-pc' || act === 'sniff-tzsp') {
  3953. document.getElementById('mangle-row-sniff')?.classList.remove('hidden');
  3954. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  3955. } else if (act === 'clear-df' || act === 'strip-ipv4-options') {
  3956. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  3957. } else if (act === 'jump') {
  3958. if (jumpBox) jumpBox.classList.remove('hidden');
  3959. } else if (act.includes('address-list') || act.includes('address list')) {
  3960. if (addrBox) addrBox.classList.remove('hidden');
  3961. }
  3962. if (act === 'log') {
  3963. const logEl = document.getElementById('mangle-modal-log');
  3964. if (logEl) logEl.checked = true;
  3965. toggleMangleField('logprefix', true);
  3966. }
  3967. }
  3968. function toggleMangleLogPrefix() {
  3969. const isLog = document.getElementById('mangle-modal-log')?.checked;
  3970. toggleMangleField('logprefix', !!isLog);
  3971. }
  3972. const allMangleFieldKeys = [
  3973. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  3974. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  3975. 'routingmark', 'conntype', 'cs', 'natstate',
  3976. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  3977. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  3978. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  3979. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  3980. 'nth', 'connlimit', 'srcaddrtype', 'dstaddrtype', 'hotspot', 'ipfragment',
  3981. 'limit', 'dstlimit', 'time', 'psd', 'logprefix'
  3982. ];
  3983. function openAddMangleModal() {
  3984. switchMangleRuleTab('general');
  3985. const badge = document.getElementById('mangle-modal-badge');
  3986. if (badge) badge.innerText = 'New...';
  3987. document.getElementById('mangle-modal-id').value = '';
  3988. document.getElementById('mangle-modal-enabled').checked = true;
  3989. document.getElementById('mangle-modal-comment').value = '';
  3990. document.getElementById('mangle-modal-chain').value = 'prerouting';
  3991. document.getElementById('mangle-modal-action').value = 'mark-connection';
  3992. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = '';
  3993. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = '';
  3994. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = '';
  3995. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = '';
  3996. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = '';
  3997. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = '';
  3998. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = '';
  3999. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = '';
  4000. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = '';
  4001. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = '';
  4002. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = '';
  4003. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = '';
  4004. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = true;
  4005. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = false;
  4006. populateInterfaceSelect('mangle-val-iniface');
  4007. populateInterfaceSelect('mangle-val-outiface');
  4008. populateAddressListSelect('mangle-val-srclist');
  4009. populateAddressListSelect('mangle-val-dstlist');
  4010. populateGeoIPSelect('mangle-val-srcgeo');
  4011. populateGeoIPSelect('mangle-val-dstgeo');
  4012. allMangleFieldKeys.forEach(k => toggleMangleField(k, false));
  4013. resetCurrentMangleRuleCounters();
  4014. toggleMangleActionFields();
  4015. document.getElementById('mangle-modal').classList.remove('hidden');
  4016. }
  4017. function openEditMangleModal(id) {
  4018. const r = (state.mangleRules || []).find(rule => rule.id === id);
  4019. if (!r) return;
  4020. switchMangleRuleTab('general');
  4021. const badge = document.getElementById('mangle-modal-badge');
  4022. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4023. document.getElementById('mangle-modal-id').value = r.id;
  4024. document.getElementById('mangle-modal-enabled').checked = !r.disabled;
  4025. document.getElementById('mangle-modal-comment').value = r.comment || '';
  4026. document.getElementById('mangle-modal-chain').value = r.chain || 'prerouting';
  4027. document.getElementById('mangle-modal-action').value = r.action || 'mark-connection';
  4028. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = r.new_connection_mark || '';
  4029. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = r.new_routing_mark || '';
  4030. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = r.new_packet_mark || '';
  4031. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = r.new_mss || '';
  4032. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = r.new_dscp != null ? r.new_dscp : '';
  4033. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = r.new_ttl || '';
  4034. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = r.new_priority || '';
  4035. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = r.route || '';
  4036. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = r.sniff_target || '';
  4037. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = r.jump_target || '';
  4038. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = r.address_list || '';
  4039. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = r.address_list_timeout || '';
  4040. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  4041. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = !!r.log;
  4042. populateInterfaceSelect('mangle-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  4043. populateInterfaceSelect('mangle-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  4044. populateAddressListSelect('mangle-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  4045. populateAddressListSelect('mangle-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  4046. populateGeoIPSelect('mangle-val-srcgeo', r.src_geoip || '');
  4047. populateGeoIPSelect('mangle-val-dstgeo', r.dst_geoip || '');
  4048. setMangleFieldVal('src', r.src_address, true);
  4049. setMangleFieldVal('dst', r.dst_address, true);
  4050. setMangleFieldVal('srclist', r.src_address_list, true);
  4051. setMangleFieldVal('dstlist', r.dst_address_list, true);
  4052. setMangleFieldVal('srcgeo', r.src_geoip, true);
  4053. setMangleFieldVal('dstgeo', r.dst_geoip, true);
  4054. if (r.protocol && r.protocol !== 'all') {
  4055. setMangleFieldVal('proto', r.protocol, true);
  4056. } else {
  4057. toggleMangleField('proto', false);
  4058. }
  4059. setMangleFieldVal('sport', r.src_port, true);
  4060. setMangleFieldVal('dport', r.dst_port, true);
  4061. setMangleFieldVal('anyport', r.any_port, true);
  4062. setMangleFieldVal('iniface', r.in_interface, true);
  4063. setMangleFieldVal('outiface', r.out_interface, true);
  4064. setMangleFieldVal('inifacelist', r.in_interface_list, true);
  4065. setMangleFieldVal('outifacelist', r.out_interface_list, true);
  4066. setMangleFieldVal('pktmark', r.packet_mark, true);
  4067. setMangleFieldVal('connmark', r.connection_mark, true);
  4068. setMangleFieldVal('routingmark', r.routing_mark, true);
  4069. setMangleFieldVal('conntype', r.connection_type, false);
  4070. // Connection State
  4071. const states = r.connection_state || [];
  4072. if (states.length > 0) {
  4073. toggleMangleField('cs', true);
  4074. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  4075. const el = document.getElementById(`mangle-modal-cs-${s}`);
  4076. if (el) el.checked = states.includes(s);
  4077. });
  4078. } else {
  4079. toggleMangleField('cs', false);
  4080. }
  4081. // Connection NAT State
  4082. const natStates = r.connection_nat_state || [];
  4083. if (natStates.length > 0) {
  4084. toggleMangleField('natstate', true);
  4085. ['srcnat', 'dstnat'].forEach(s => {
  4086. const el = document.getElementById(`mangle-modal-nat-${s}`);
  4087. if (el) el.checked = natStates.includes(s);
  4088. });
  4089. } else {
  4090. toggleMangleField('natstate', false);
  4091. }
  4092. // Advanced tab fields
  4093. setMangleFieldVal('layer7', r.layer7_protocol, false);
  4094. setMangleFieldVal('content', r.content, false);
  4095. setMangleFieldVal('connbytes', r.connection_bytes, false);
  4096. setMangleFieldVal('connrate', r.connection_rate, false);
  4097. setMangleFieldVal('pcc', r.pcc, false);
  4098. setMangleFieldVal('srcmac', r.src_mac_address, true);
  4099. setMangleFieldVal('outbridgeport', r.out_bridge_port, false);
  4100. setMangleFieldVal('inbridgeport', r.in_bridge_port, false);
  4101. setMangleFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  4102. setMangleFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  4103. setMangleFieldVal('ipsec', r.ipsec_policy, false);
  4104. setMangleFieldVal('tlshost', r.tls_host, false);
  4105. setMangleFieldVal('ingresspriority', r.ingress_priority, false);
  4106. setMangleFieldVal('priority', r.priority, false);
  4107. setMangleFieldVal('dscp', r.dscp, false);
  4108. setMangleFieldVal('tcpmss', r.tcp_mss, false);
  4109. if (r.tos) {
  4110. const tosEl = document.getElementById('mangle-val-tos');
  4111. if (tosEl) tosEl.value = r.tos;
  4112. }
  4113. setMangleFieldVal('pktsize', r.packet_size, false);
  4114. setMangleFieldVal('random', r.random, false);
  4115. setMangleFieldVal('tcpflags', r.tcp_flags, false);
  4116. setMangleFieldVal('icmpoptions', r.icmp_options, false);
  4117. setMangleFieldVal('ipv4options', r.ipv4_options, false);
  4118. setMangleFieldVal('ttl', r.ttl, false);
  4119. // Extra tab fields
  4120. setMangleFieldVal('nth', r.nth, false);
  4121. setMangleFieldVal('connlimit', r.connection_limit, false);
  4122. setMangleFieldVal('srcaddrtype', r.src_address_type, false);
  4123. setMangleFieldVal('dstaddrtype', r.dst_address_type, false);
  4124. setMangleFieldVal('hotspot', r.hotspot, false);
  4125. setMangleFieldVal('ipfragment', r.ip_fragment, false);
  4126. setMangleFieldVal('limit', r.limit, false);
  4127. setMangleFieldVal('dstlimit', r.dst_limit, false);
  4128. setMangleFieldVal('time', r.time, false);
  4129. setMangleFieldVal('psd', r.psd, false);
  4130. // Action fields
  4131. if (r.jump_target) {
  4132. const jtEl = document.getElementById('mangle-modal-jumptarget');
  4133. if (jtEl) jtEl.value = r.jump_target;
  4134. }
  4135. if (r.address_list) {
  4136. const alEl = document.getElementById('mangle-modal-action-addrlist');
  4137. if (alEl) alEl.value = r.address_list;
  4138. }
  4139. if (r.address_list_timeout) {
  4140. const toEl = document.getElementById('mangle-modal-action-timeout');
  4141. if (toEl) toEl.value = r.address_list_timeout;
  4142. }
  4143. setMangleFieldVal('logprefix', r.log_prefix, false);
  4144. // Statistics
  4145. const bEl = document.getElementById('mangle-stat-bytes');
  4146. const pEl = document.getElementById('mangle-stat-packets');
  4147. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  4148. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  4149. state.mangleLastBytes = r.bytes || 0;
  4150. state.mangleLastPackets = r.packets || 0;
  4151. state.mangleLastTimestamp = Date.now();
  4152. state.mangleStatRateHistory = new Array(30).fill(0);
  4153. state.mangleStatPktHistory = new Array(30).fill(0);
  4154. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4155. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4156. toggleMangleActionFields();
  4157. document.getElementById('mangle-modal').classList.remove('hidden');
  4158. }
  4159. function closeMangleModal() {
  4160. stopMangleStatPolling();
  4161. document.getElementById('mangle-modal').classList.add('hidden');
  4162. }
  4163. function copyMangleRule() {
  4164. document.getElementById('mangle-modal-id').value = '';
  4165. const badge = document.getElementById('mangle-modal-badge');
  4166. if (badge) badge.innerText = 'New...';
  4167. showToast('Rule Cloned', 'Ready to save as a new Mangle rule copy', 'info');
  4168. }
  4169. function resetCurrentMangleRuleCounters() {
  4170. state.mangleStatRateHistory = new Array(30).fill(0);
  4171. state.mangleStatPktHistory = new Array(30).fill(0);
  4172. state.mangleLastBytes = 0;
  4173. state.mangleLastPackets = 0;
  4174. state.mangleLastTimestamp = Date.now();
  4175. const bEl = document.getElementById('mangle-stat-bytes');
  4176. const pEl = document.getElementById('mangle-stat-packets');
  4177. const rEl = document.getElementById('mangle-stat-rate');
  4178. const prEl = document.getElementById('mangle-stat-pktrate');
  4179. if (bEl) bEl.value = '0 B';
  4180. if (pEl) pEl.value = '0';
  4181. if (rEl) rEl.value = '0 bps';
  4182. if (prEl) prEl.value = '0 p/s';
  4183. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4184. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4185. showToast('Counters Reset', 'Mangle rule counter display reset to 0', 'info');
  4186. }
  4187. async function applyMangleRule(closeAfter = false) {
  4188. const id = document.getElementById('mangle-modal-id').value;
  4189. const chain = document.getElementById('mangle-modal-chain').value;
  4190. const action = document.getElementById('mangle-modal-action').value;
  4191. const comment = document.getElementById('mangle-modal-comment').value.trim();
  4192. const enabled = document.getElementById('mangle-modal-enabled').checked;
  4193. const src = getMangleFieldVal('src', true);
  4194. const dst = getMangleFieldVal('dst', true);
  4195. const srclist = getMangleFieldVal('srclist', true);
  4196. const dstlist = getMangleFieldVal('dstlist', true);
  4197. const srcgeo = getMangleFieldVal('srcgeo', true);
  4198. const dstgeo = getMangleFieldVal('dstgeo', true);
  4199. const proto = getMangleFieldVal('proto', true);
  4200. const sport = getMangleFieldVal('sport', true);
  4201. const dport = getMangleFieldVal('dport', true);
  4202. const anyport = getMangleFieldVal('anyport', true);
  4203. const iniface = getMangleFieldVal('iniface', true);
  4204. const outiface = getMangleFieldVal('outiface', true);
  4205. const inifacelist = getMangleFieldVal('inifacelist', true);
  4206. const outifacelist = getMangleFieldVal('outifacelist', true);
  4207. const pktmark = getMangleFieldVal('pktmark', true);
  4208. const connmark = getMangleFieldVal('connmark', true);
  4209. const routingmark = getMangleFieldVal('routingmark', true);
  4210. const conntype = getMangleFieldVal('conntype', false);
  4211. const states = [];
  4212. const csBox = document.getElementById('mangle-field-cs');
  4213. if (csBox && !csBox.classList.contains('hidden')) {
  4214. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  4215. if (document.getElementById(`mangle-modal-cs-${s}`)?.checked) states.push(s);
  4216. });
  4217. }
  4218. const natStates = [];
  4219. const natBox = document.getElementById('mangle-field-natstate');
  4220. if (natBox && !natBox.classList.contains('hidden')) {
  4221. ['srcnat', 'dstnat'].forEach(s => {
  4222. if (document.getElementById(`mangle-modal-nat-${s}`)?.checked) natStates.push(s);
  4223. });
  4224. }
  4225. const payload = {
  4226. id,
  4227. chain,
  4228. action,
  4229. protocol: proto || 'all',
  4230. src_address: src,
  4231. dst_address: dst,
  4232. src_port: sport,
  4233. dst_port: dport,
  4234. any_port: anyport,
  4235. in_interface: iniface,
  4236. out_interface: outiface,
  4237. in_interface_list: inifacelist,
  4238. out_interface_list: outifacelist,
  4239. packet_mark: pktmark,
  4240. connection_mark: connmark,
  4241. routing_mark: routingmark,
  4242. connection_type: conntype,
  4243. connection_state: states,
  4244. connection_nat_state: natStates,
  4245. src_address_list: srclist,
  4246. dst_address_list: dstlist,
  4247. src_geoip: srcgeo,
  4248. dst_geoip: dstgeo,
  4249. comment,
  4250. disabled: !enabled,
  4251. // Advanced tab
  4252. layer7_protocol: getMangleFieldVal('layer7', false),
  4253. content: getMangleFieldVal('content', false),
  4254. connection_bytes: getMangleFieldVal('connbytes', false),
  4255. connection_rate: getMangleFieldVal('connrate', false),
  4256. pcc: getMangleFieldVal('pcc', false),
  4257. src_mac_address: getMangleFieldVal('srcmac', true),
  4258. out_bridge_port: getMangleFieldVal('outbridgeport', false),
  4259. in_bridge_port: getMangleFieldVal('inbridgeport', false),
  4260. in_bridge_port_list: getMangleFieldVal('inbridgeportlist', false),
  4261. out_bridge_port_list: getMangleFieldVal('outbridgeportlist', false),
  4262. ipsec_policy: getMangleFieldVal('ipsec', false),
  4263. tls_host: getMangleFieldVal('tlshost', false),
  4264. ingress_priority: getMangleFieldVal('ingresspriority', false),
  4265. priority: getMangleFieldVal('priority', false),
  4266. dscp: getMangleFieldVal('dscp', false),
  4267. tcp_mss: getMangleFieldVal('tcpmss', false),
  4268. tos: document.getElementById('mangle-val-tos')?.value || '',
  4269. packet_size: getMangleFieldVal('pktsize', false),
  4270. random: getMangleFieldVal('random', false),
  4271. tcp_flags: getMangleFieldVal('tcpflags', false),
  4272. icmp_options: getMangleFieldVal('icmpoptions', false),
  4273. ipv4_options: getMangleFieldVal('ipv4options', false),
  4274. ttl: getMangleFieldVal('ttl', false),
  4275. // Extra tab
  4276. nth: getMangleFieldVal('nth', false),
  4277. connection_limit: getMangleFieldVal('connlimit', false),
  4278. src_address_type: getMangleFieldVal('srcaddrtype', false),
  4279. dst_address_type: getMangleFieldVal('dstaddrtype', false),
  4280. hotspot: getMangleFieldVal('hotspot', false),
  4281. ip_fragment: getMangleFieldVal('ipfragment', false),
  4282. limit: getMangleFieldVal('limit', false),
  4283. dst_limit: getMangleFieldVal('dstlimit', false),
  4284. time: getMangleFieldVal('time', false),
  4285. psd: getMangleFieldVal('psd', false),
  4286. // Action tab
  4287. new_connection_mark: action === 'mark-connection' ? (document.getElementById('mangle-modal-newconnmark')?.value.trim() || '') : '',
  4288. new_routing_mark: action === 'mark-routing' ? (document.getElementById('mangle-modal-newroutingmark')?.value.trim() || '') : '',
  4289. new_packet_mark: action === 'mark-packet' ? (document.getElementById('mangle-modal-newpktmark')?.value.trim() || '') : '',
  4290. new_mss: action === 'change-mss' ? (document.getElementById('mangle-modal-newmss')?.value.trim() || '') : '',
  4291. new_dscp: action === 'change-dscp' ? parseInt(document.getElementById('mangle-modal-newdscp')?.value || '0', 10) : 0,
  4292. new_ttl: action === 'change-ttl' ? (document.getElementById('mangle-modal-newttl')?.value.trim() || '') : '',
  4293. new_priority: action === 'set-priority' ? (document.getElementById('mangle-modal-newpriority')?.value.trim() || '') : '',
  4294. route: action === 'route' ? (document.getElementById('mangle-modal-route')?.value.trim() || '') : '',
  4295. sniff_target: (action === 'sniff-pc' || action === 'sniff-tzsp') ? (document.getElementById('mangle-modal-sniff')?.value.trim() || '') : '',
  4296. passthrough: document.getElementById('mangle-modal-passthrough')?.checked ?? true,
  4297. jump_target: action === 'jump' ? (document.getElementById('mangle-modal-jumptarget')?.value || '') : '',
  4298. address_list: action.includes('address') ? (document.getElementById('mangle-modal-action-addrlist')?.value || '') : '',
  4299. address_list_timeout: action.includes('address') ? (document.getElementById('mangle-modal-action-timeout')?.value || '') : '',
  4300. log: document.getElementById('mangle-modal-log')?.checked || false,
  4301. log_prefix: getMangleFieldVal('logprefix', false)
  4302. };
  4303. try {
  4304. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  4305. method: 'POST',
  4306. headers: { 'Content-Type': 'application/json' },
  4307. body: JSON.stringify(payload)
  4308. });
  4309. if (res.ok) {
  4310. const data = await res.json();
  4311. showToast('Mangle Rule Saved', 'Marking rule updated', 'success');
  4312. loadFirewall(false);
  4313. if (closeAfter) {
  4314. closeMangleModal();
  4315. } else {
  4316. if (data.id) {
  4317. document.getElementById('mangle-modal-id').value = data.id;
  4318. const badge = document.getElementById('mangle-modal-badge');
  4319. if (badge) badge.innerText = `#${data.id}`;
  4320. }
  4321. }
  4322. } else {
  4323. const err = await res.json();
  4324. showToast('Error', err.message || 'Failed to save mangle rule', 'error');
  4325. }
  4326. } catch (err) {
  4327. showToast('Error', err.message, 'error');
  4328. }
  4329. }
  4330. function submitSaveMangleRule(e) {
  4331. if (e && e.preventDefault) e.preventDefault();
  4332. return applyMangleRule(true);
  4333. }
  4334. function startMangleStatPolling() {
  4335. stopMangleStatPolling();
  4336. pollMangleRuleStats();
  4337. state.mangleStatInterval = setInterval(pollMangleRuleStats, 1000);
  4338. }
  4339. function stopMangleStatPolling() {
  4340. if (state.mangleStatInterval) {
  4341. clearInterval(state.mangleStatInterval);
  4342. state.mangleStatInterval = null;
  4343. }
  4344. }
  4345. async function pollMangleRuleStats() {
  4346. const id = document.getElementById('mangle-modal-id')?.value;
  4347. if (!id) {
  4348. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory || new Array(30).fill(0), 'bps', 'mangle-stat-legend-rate');
  4349. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory || new Array(30).fill(0), 'p/s', 'mangle-stat-legend-pktrate');
  4350. return;
  4351. }
  4352. try {
  4353. const res = await fetch(`${API_BASE}/firewall/mangle`);
  4354. if (!res.ok) return;
  4355. const rules = await res.json();
  4356. const r = rules.find(x => x.id === id);
  4357. if (!r) return;
  4358. const now = Date.now();
  4359. const dt = Math.max(0.2, (now - (state.mangleLastTimestamp || now)) / 1000);
  4360. state.mangleLastTimestamp = now;
  4361. const curBytes = r.bytes || 0;
  4362. const curPackets = r.packets || 0;
  4363. const deltaBytes = Math.max(0, curBytes - (state.mangleLastBytes || curBytes));
  4364. const deltaPkts = Math.max(0, curPackets - (state.mangleLastPackets || curPackets));
  4365. state.mangleLastBytes = curBytes;
  4366. state.mangleLastPackets = curPackets;
  4367. const rateBps = Math.round((deltaBytes * 8) / dt);
  4368. const ratePkt = Math.round(deltaPkts / dt);
  4369. if (!state.mangleStatRateHistory) state.mangleStatRateHistory = new Array(30).fill(0);
  4370. if (!state.mangleStatPktHistory) state.mangleStatPktHistory = new Array(30).fill(0);
  4371. state.mangleStatRateHistory.push(rateBps);
  4372. if (state.mangleStatRateHistory.length > 30) state.mangleStatRateHistory.shift();
  4373. state.mangleStatPktHistory.push(ratePkt);
  4374. if (state.mangleStatPktHistory.length > 30) state.mangleStatPktHistory.shift();
  4375. const bEl = document.getElementById('mangle-stat-bytes');
  4376. const pEl = document.getElementById('mangle-stat-packets');
  4377. const rEl = document.getElementById('mangle-stat-rate');
  4378. const prEl = document.getElementById('mangle-stat-pktrate');
  4379. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4380. if (pEl) pEl.value = curPackets.toLocaleString();
  4381. if (rEl) rEl.value = formatBps(rateBps);
  4382. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4383. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4384. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4385. } catch (e) {
  4386. console.error('Error polling Mangle rule stats', e);
  4387. }
  4388. }
  4389. async function moveMangleRule(id, dir) {
  4390. try {
  4391. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  4392. method: 'POST',
  4393. headers: { 'Content-Type': 'application/json' },
  4394. body: JSON.stringify({ direction: dir })
  4395. });
  4396. if (res.ok) loadFirewall(false);
  4397. } catch (err) {
  4398. showToast('Error', err.message, 'error');
  4399. }
  4400. }
  4401. async function toggleMangleRuleState(id, disabled) {
  4402. try {
  4403. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  4404. method: 'POST',
  4405. headers: { 'Content-Type': 'application/json' },
  4406. body: JSON.stringify({ disabled })
  4407. });
  4408. if (res.ok) loadFirewall(false);
  4409. } catch (err) {
  4410. showToast('Error', err.message, 'error');
  4411. }
  4412. }
  4413. async function deleteMangleRule(id) {
  4414. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  4415. try {
  4416. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4417. if (res.ok) {
  4418. showToast('Deleted', 'Mangle rule removed', 'success');
  4419. loadFirewall(false);
  4420. }
  4421. } catch (err) {
  4422. showToast('Error', err.message, 'error');
  4423. }
  4424. }
  4425. // ----------------- Address Lists -----------------
  4426. function renderAddressLists() {
  4427. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  4428. const tbody = document.getElementById('addrlist-table-body');
  4429. const empty = document.getElementById('addrlist-empty');
  4430. if (!tbody) return;
  4431. tbody.innerHTML = '';
  4432. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  4433. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries`;
  4434. // Update filter select
  4435. const sel = document.getElementById('addrlist-filter-name');
  4436. if (sel) {
  4437. const cur = sel.value;
  4438. sel.innerHTML = '<option value="">All Lists</option>';
  4439. const set = new Set((state.addressLists || []).map(a => a.name));
  4440. set.forEach(n => {
  4441. const opt = document.createElement('option');
  4442. opt.value = n;
  4443. opt.innerText = n;
  4444. if (n === cur) opt.selected = true;
  4445. sel.appendChild(opt);
  4446. });
  4447. }
  4448. if (entries.length === 0) {
  4449. empty?.classList.remove('hidden');
  4450. return;
  4451. }
  4452. empty?.classList.add('hidden');
  4453. entries.forEach((e, idx) => {
  4454. const tr = document.createElement('tr');
  4455. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
  4456. tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
  4457. tr.innerHTML = `
  4458. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  4459. <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>
  4460. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  4461. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  4462. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]">${e.comment || '-'}</td>
  4463. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  4464. <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>
  4465. <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
  4466. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4467. </td>
  4468. `;
  4469. tbody.appendChild(tr);
  4470. });
  4471. populateCommonAddrListDatalist();
  4472. }
  4473. function openAddAddrListModal() {
  4474. document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
  4475. document.getElementById('addrlist-modal-id').value = '';
  4476. document.getElementById('addrlist-modal-name').value = '';
  4477. document.getElementById('addrlist-modal-addr').value = '';
  4478. document.getElementById('addrlist-modal-comment').value = '';
  4479. document.getElementById('addrlist-modal-disabled').checked = false;
  4480. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  4481. if (submitBtn) submitBtn.innerText = 'Add to List';
  4482. document.getElementById('addrlist-modal').classList.remove('hidden');
  4483. }
  4484. function openEditAddrListModal(id) {
  4485. const e = (state.addressLists || []).find(item => item.id === id);
  4486. if (!e) return;
  4487. document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
  4488. document.getElementById('addrlist-modal-id').value = e.id;
  4489. document.getElementById('addrlist-modal-name').value = e.name;
  4490. document.getElementById('addrlist-modal-addr').value = e.address;
  4491. document.getElementById('addrlist-modal-comment').value = e.comment || '';
  4492. document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
  4493. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  4494. if (submitBtn) submitBtn.innerText = 'Save Changes';
  4495. document.getElementById('addrlist-modal').classList.remove('hidden');
  4496. }
  4497. function closeAddrListModal() {
  4498. document.getElementById('addrlist-modal').classList.add('hidden');
  4499. }
  4500. async function submitSaveAddrList(e) {
  4501. e.preventDefault();
  4502. const id = document.getElementById('addrlist-modal-id').value;
  4503. const name = document.getElementById('addrlist-modal-name').value.trim();
  4504. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  4505. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  4506. const disabled = document.getElementById('addrlist-modal-disabled').checked;
  4507. try {
  4508. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  4509. method: 'POST',
  4510. headers: { 'Content-Type': 'application/json' },
  4511. body: JSON.stringify({ id, name, address: addr, comment, disabled })
  4512. });
  4513. if (res.ok) {
  4514. showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
  4515. closeAddrListModal();
  4516. loadFirewall(false);
  4517. } else {
  4518. const err = await res.json();
  4519. showToast('Error', err.message || 'Failed to save address list', 'error');
  4520. }
  4521. } catch (err) {
  4522. showToast('Error', err.message, 'error');
  4523. }
  4524. }
  4525. async function toggleAddrListState(id, disabled) {
  4526. try {
  4527. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
  4528. method: 'POST',
  4529. headers: { 'Content-Type': 'application/json' },
  4530. body: JSON.stringify({ disabled })
  4531. });
  4532. if (res.ok) {
  4533. loadFirewall(false);
  4534. }
  4535. } catch (err) {
  4536. showToast('Error', err.message, 'error');
  4537. }
  4538. }
  4539. async function deleteAddrList(id) {
  4540. if (!confirm('Are you sure you want to delete this address list item?')) return;
  4541. try {
  4542. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4543. if (res.ok) {
  4544. showToast('Deleted', 'Address list item removed', 'info');
  4545. loadFirewall(false);
  4546. }
  4547. } catch (err) {
  4548. showToast('Error', err.message, 'error');
  4549. }
  4550. }
  4551. // ----------------- Geo-Location IP Management -----------------
  4552. async function loadGeoIP() {
  4553. try {
  4554. const [statusRes, countriesRes] = await Promise.all([
  4555. fetch(`${API_BASE}/firewall/geoip/status`),
  4556. fetch(`${API_BASE}/firewall/geoip/countries`)
  4557. ]);
  4558. if (statusRes.ok) state.geoStatus = await statusRes.json();
  4559. if (countriesRes.ok) state.geoCountries = await countriesRes.json();
  4560. updateGeoHeader();
  4561. renderGeoCountries();
  4562. } catch (err) {
  4563. console.error('Failed to load GeoIP:', err);
  4564. }
  4565. }
  4566. function getGeoUsageMap() {
  4567. const usage = {};
  4568. const checkRule = (r, type) => {
  4569. ['src_geoip', 'dst_geoip'].forEach(field => {
  4570. let val = (r && r[field]) || '';
  4571. let code = val.replace(/^!/, '').replace(/^geo:/, '').replace(/^geo_/, '').toUpperCase().trim();
  4572. if (code) {
  4573. if (!usage[code]) usage[code] = [];
  4574. const label = `${type} #${r.priority !== undefined ? r.priority : (r.id || '')}`;
  4575. if (!usage[code].includes(label)) usage[code].push(label);
  4576. }
  4577. });
  4578. };
  4579. (state.filterRules || []).forEach(r => checkRule(r, 'Filter'));
  4580. (state.natRules || []).forEach(r => checkRule(r, 'NAT'));
  4581. (state.mangleRules || []).forEach(r => checkRule(r, 'Mangle'));
  4582. return usage;
  4583. }
  4584. function updateGeoHeader() {
  4585. const s = state.geoStatus || {};
  4586. const statusBadge = document.getElementById('geo-status-badge');
  4587. if (statusBadge) {
  4588. statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
  4589. statusBadge.className = s.auto_update
  4590. ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
  4591. : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
  4592. }
  4593. const intervalLabel = document.getElementById('geo-interval-label');
  4594. if (intervalLabel) {
  4595. intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
  4596. }
  4597. const usageMap = getGeoUsageMap();
  4598. const inUseCount = Object.keys(usageMap).length;
  4599. const activeCountEl = document.getElementById('geo-stat-active-countries');
  4600. if (activeCountEl) activeCountEl.innerText = inUseCount.toLocaleString();
  4601. const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
  4602. if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
  4603. const lastSyncEl = document.getElementById('geo-stat-last-sync');
  4604. if (lastSyncEl) {
  4605. if (s.last_updated && !s.last_updated.startsWith('0001')) {
  4606. const d = new Date(s.last_updated);
  4607. lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  4608. } else {
  4609. lastSyncEl.innerText = 'Never (Sync Pending)';
  4610. }
  4611. }
  4612. const nextSyncEl = document.getElementById('geo-stat-next-sync');
  4613. if (nextSyncEl) {
  4614. if (s.next_update && !s.next_update.startsWith('0001')) {
  4615. const d = new Date(s.next_update);
  4616. nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  4617. } else {
  4618. nextSyncEl.innerText = '-';
  4619. }
  4620. }
  4621. const badge = document.getElementById('fw-badge-geo');
  4622. if (badge) badge.innerText = inUseCount || (state.geoCountries || []).filter(c => c.subnet_count > 0).length || 0;
  4623. }
  4624. function renderGeoCountries() {
  4625. const tbody = document.getElementById('geo-table-body');
  4626. const empty = document.getElementById('geo-empty');
  4627. if (!tbody) return;
  4628. tbody.innerHTML = '';
  4629. const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
  4630. const continent = document.getElementById('geo-continent-filter')?.value || '';
  4631. const inUseOnly = document.getElementById('geo-filter-inuse-only')?.checked;
  4632. const cachedOnly = document.getElementById('geo-filter-cached-only')?.checked;
  4633. const usageMap = getGeoUsageMap();
  4634. const countries = (state.geoCountries || []).filter(c => {
  4635. const isUsed = !!usageMap[c.code];
  4636. if (inUseOnly && !isUsed) return false;
  4637. if (cachedOnly && (!c.subnet_count || c.subnet_count === 0)) return false;
  4638. if (continent && c.continent !== continent) return false;
  4639. if (q) {
  4640. const matchCode = c.code.toLowerCase().includes(q);
  4641. const matchName = c.name.toLowerCase().includes(q);
  4642. if (!matchCode && !matchName) return false;
  4643. }
  4644. return true;
  4645. });
  4646. if (countries.length === 0) {
  4647. empty?.classList.remove('hidden');
  4648. return;
  4649. }
  4650. empty?.classList.add('hidden');
  4651. countries.forEach(c => {
  4652. const tr = document.createElement('tr');
  4653. const isUsed = !!usageMap[c.code];
  4654. const rulesUsing = usageMap[c.code] || [];
  4655. tr.className = `hover:bg-slate-800/40 transition text-xs ${isUsed ? 'bg-emerald-950/20' : ''}`;
  4656. let statusHtml = '';
  4657. if (isUsed) {
  4658. 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>`;
  4659. } else if (c.subnet_count > 0) {
  4660. 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>';
  4661. } else {
  4662. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-slate-500 bg-slate-800/60">READY</span>';
  4663. }
  4664. tr.innerHTML = `
  4665. <td class="py-2.5 px-3 text-center">
  4666. <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'}">
  4667. ${c.code}
  4668. </span>
  4669. </td>
  4670. <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
  4671. <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
  4672. <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
  4673. ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
  4674. </td>
  4675. <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
  4676. <td class="py-2.5 px-3">
  4677. ${statusHtml}
  4678. </td>
  4679. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  4680. <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>
  4681. <button onclick="viewGeoSubnets('${c.code}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
  4682. </td>
  4683. `;
  4684. tbody.appendChild(tr);
  4685. });
  4686. }
  4687. function quickFilterGeo(preset) {
  4688. const searchInput = document.getElementById('geo-search-input');
  4689. const continentSel = document.getElementById('geo-continent-filter');
  4690. const inUseCheck = document.getElementById('geo-filter-inuse-only');
  4691. const cachedCheck = document.getElementById('geo-filter-cached-only');
  4692. if (searchInput) searchInput.value = '';
  4693. if (continentSel) continentSel.value = '';
  4694. if (inUseCheck) inUseCheck.checked = false;
  4695. if (cachedCheck) cachedCheck.checked = false;
  4696. if (preset === 'GR') {
  4697. if (searchInput) searchInput.value = 'Greece';
  4698. } else if (preset === 'Europe') {
  4699. if (continentSel) continentSel.value = 'Europe';
  4700. } else if (preset === 'HIGHRISK') {
  4701. if (searchInput) searchInput.value = 'China';
  4702. }
  4703. renderGeoCountries();
  4704. }
  4705. async function toggleGeoCountry(code, enabled) {
  4706. try {
  4707. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
  4708. method: 'POST',
  4709. headers: { 'Content-Type': 'application/json' },
  4710. body: JSON.stringify({ enabled })
  4711. });
  4712. if (res.ok) {
  4713. showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
  4714. loadGeoIP();
  4715. } else {
  4716. const err = await res.json();
  4717. showToast('Error', err.message || 'Failed to toggle country', 'error');
  4718. }
  4719. } catch (err) {
  4720. showToast('Error', err.message, 'error');
  4721. }
  4722. }
  4723. async function updateGeoCountry(code) {
  4724. try {
  4725. showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
  4726. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
  4727. if (res.ok) {
  4728. const data = await res.json();
  4729. showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
  4730. loadGeoIP();
  4731. } else {
  4732. const err = await res.json();
  4733. showToast('Sync Error', err.message || 'Failed to sync country', 'error');
  4734. }
  4735. } catch (err) {
  4736. showToast('Error', err.message, 'error');
  4737. }
  4738. }
  4739. async function triggerGeoUpdateNow() {
  4740. const spinner = document.getElementById('geo-update-spinner');
  4741. if (spinner) spinner.classList.remove('hidden');
  4742. try {
  4743. const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
  4744. if (res.ok) {
  4745. showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
  4746. setTimeout(() => {
  4747. loadGeoIP();
  4748. if (spinner) spinner.classList.add('hidden');
  4749. }, 2500);
  4750. } else {
  4751. const err = await res.json();
  4752. showToast('Notice', err.message || 'Update in progress', 'info');
  4753. if (spinner) spinner.classList.add('hidden');
  4754. }
  4755. } catch (err) {
  4756. showToast('Error', err.message, 'error');
  4757. if (spinner) spinner.classList.add('hidden');
  4758. }
  4759. }
  4760. async function applyGeoPreset(preset) {
  4761. try {
  4762. const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
  4763. method: 'POST',
  4764. headers: { 'Content-Type': 'application/json' },
  4765. body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
  4766. });
  4767. if (res.ok) {
  4768. showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
  4769. loadGeoIP();
  4770. }
  4771. } catch (err) {
  4772. showToast('Error', err.message, 'error');
  4773. }
  4774. }
  4775. function openGeoIntervalModal() {
  4776. const s = state.geoStatus || {};
  4777. document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
  4778. const sel = document.getElementById('geo-cfg-interval');
  4779. const customBox = document.getElementById('geo-cfg-custom-box');
  4780. const customHoursInput = document.getElementById('geo-cfg-custom-hours');
  4781. const curHours = s.interval_hours || 24;
  4782. const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
  4783. if (matchOption) {
  4784. sel.value = String(curHours);
  4785. customBox.classList.add('hidden');
  4786. } else {
  4787. sel.value = 'custom';
  4788. customHoursInput.value = curHours;
  4789. customBox.classList.remove('hidden');
  4790. }
  4791. document.getElementById('geo-interval-modal').classList.remove('hidden');
  4792. }
  4793. function closeGeoIntervalModal() {
  4794. document.getElementById('geo-interval-modal').classList.add('hidden');
  4795. }
  4796. function toggleCustomGeoInterval() {
  4797. const val = document.getElementById('geo-cfg-interval').value;
  4798. const customBox = document.getElementById('geo-cfg-custom-box');
  4799. if (val === 'custom') {
  4800. customBox.classList.remove('hidden');
  4801. } else {
  4802. customBox.classList.add('hidden');
  4803. }
  4804. }
  4805. async function submitGeoIntervalSettings(e) {
  4806. e.preventDefault();
  4807. const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
  4808. const intervalVal = document.getElementById('geo-cfg-interval').value;
  4809. let hours = 24;
  4810. if (intervalVal === 'custom') {
  4811. hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
  4812. } else {
  4813. hours = parseInt(intervalVal, 10) || 24;
  4814. }
  4815. try {
  4816. const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
  4817. method: 'POST',
  4818. headers: { 'Content-Type': 'application/json' },
  4819. body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
  4820. });
  4821. if (res.ok) {
  4822. showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
  4823. closeGeoIntervalModal();
  4824. loadGeoIP();
  4825. } else {
  4826. const err = await res.json();
  4827. showToast('Error', err.message || 'Failed to save schedule', 'error');
  4828. }
  4829. } catch (err) {
  4830. showToast('Error', err.message, 'error');
  4831. }
  4832. }
  4833. async function viewGeoSubnets(code, name) {
  4834. if (!name) {
  4835. const found = (state.geoCountries || []).find(x => x.code === code);
  4836. name = found ? found.name : code;
  4837. }
  4838. document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
  4839. document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
  4840. const listEl = document.getElementById('geo-subnets-list');
  4841. listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
  4842. document.getElementById('geo-subnets-modal').classList.remove('hidden');
  4843. try {
  4844. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
  4845. if (res.ok) {
  4846. const data = await res.json();
  4847. const subnets = data.subnets || [];
  4848. if (subnets.length === 0) {
  4849. listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
  4850. } else {
  4851. listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
  4852. }
  4853. } else {
  4854. listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
  4855. }
  4856. } catch (err) {
  4857. listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
  4858. }
  4859. }
  4860. function closeGeoSubnetsModal() {
  4861. document.getElementById('geo-subnets-modal').classList.add('hidden');
  4862. }
  4863. // ----------------- Active Connections Tracking -----------------
  4864. async function loadConnections() {
  4865. try {
  4866. const res = await fetch(`${API_BASE}/firewall/connections`);
  4867. const data = await res.json();
  4868. state.connections = Array.isArray(data) ? data : [];
  4869. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  4870. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  4871. renderConnections();
  4872. } catch (err) {
  4873. console.error('Failed to load connections:', err);
  4874. }
  4875. }
  4876. function renderConnections() {
  4877. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  4878. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  4879. const tbody = document.getElementById('conns-table-body');
  4880. const empty = document.getElementById('conns-empty');
  4881. if (!tbody) return;
  4882. tbody.innerHTML = '';
  4883. const conns = (state.connections || []).filter(c => {
  4884. if (protoFilter && c.protocol !== protoFilter) return false;
  4885. if (search) {
  4886. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  4887. if (!line.includes(search)) return false;
  4888. }
  4889. return true;
  4890. });
  4891. if (conns.length === 0) {
  4892. empty?.classList.remove('hidden');
  4893. return;
  4894. }
  4895. empty?.classList.add('hidden');
  4896. conns.slice(0, 150).forEach(c => {
  4897. const tr = document.createElement('tr');
  4898. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  4899. let stateColor = 'text-slate-400';
  4900. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  4901. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  4902. tr.innerHTML = `
  4903. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  4904. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  4905. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  4906. <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>
  4907. <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>
  4908. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  4909. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  4910. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  4911. <td class="py-2.5 px-3 text-right font-sans">
  4912. <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>
  4913. </td>
  4914. `;
  4915. tbody.appendChild(tr);
  4916. });
  4917. }
  4918. async function killConnection(protocol, src, sport, dst, dport) {
  4919. try {
  4920. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  4921. method: 'POST',
  4922. headers: { 'Content-Type': 'application/json' },
  4923. body: JSON.stringify({ protocol, src, sport, dst, dport })
  4924. });
  4925. if (res.ok) {
  4926. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  4927. loadConnections();
  4928. }
  4929. } catch (err) {
  4930. showToast('Error', err.message, 'error');
  4931. }
  4932. }
  4933. async function resetFirewallCounters() {
  4934. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  4935. try {
  4936. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  4937. if (res.ok) {
  4938. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  4939. loadFirewall(false);
  4940. }
  4941. } catch (err) {
  4942. showToast('Error', err.message, 'error');
  4943. }
  4944. }
  4945. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  4946. function switchRoutesSubTab(tab) {
  4947. state.routesSubTab = tab;
  4948. const tabs = ['routes', 'rules', 'tables'];
  4949. tabs.forEach(t => {
  4950. const panel = document.getElementById(`routes-subtab-${t}`);
  4951. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  4952. if (panel) {
  4953. if (t === tab) panel.classList.remove('hidden');
  4954. else panel.classList.add('hidden');
  4955. }
  4956. if (btn) {
  4957. if (t === tab) {
  4958. 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';
  4959. } else {
  4960. 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';
  4961. }
  4962. }
  4963. });
  4964. setTimeout(initTableSorting, 50);
  4965. }
  4966. async function loadRoutes() {
  4967. try {
  4968. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  4969. fetch(`${API_BASE}/routes`),
  4970. fetch(`${API_BASE}/routing/rules`),
  4971. fetch(`${API_BASE}/routing/tables`)
  4972. ]);
  4973. if (routesRes.ok) state.routes = await routesRes.json();
  4974. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  4975. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  4976. const bRoutes = document.getElementById('routes-badge-routes');
  4977. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  4978. const showSystem = document.getElementById('prule-show-system')?.checked;
  4979. const userRules = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  4980. const bRules = document.getElementById('routes-badge-rules');
  4981. if (bRules) bRules.innerText = userRules.length;
  4982. const bTables = document.getElementById('routes-badge-tables');
  4983. if (bTables) bTables.innerText = (state.routingTables || []).length;
  4984. const bRoutesCount = document.getElementById('badge-routes-count');
  4985. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  4986. renderRoutesList();
  4987. renderPolicyRules();
  4988. renderRoutingTables();
  4989. } catch (err) {
  4990. console.error('Failed to load routing:', err);
  4991. }
  4992. }
  4993. function renderRoutesList() {
  4994. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  4995. const tbody = document.getElementById('routes-table-body');
  4996. const empty = document.getElementById('routes-empty');
  4997. if (!tbody) return;
  4998. tbody.innerHTML = '';
  4999. // Update table filter select
  5000. const sel = document.getElementById('routes-filter-table');
  5001. if (sel) {
  5002. const cur = sel.value;
  5003. sel.innerHTML = '<option value="">All Tables</option>';
  5004. (state.routingTables || []).forEach(t => {
  5005. const opt = document.createElement('option');
  5006. opt.value = t.name;
  5007. opt.innerText = t.name;
  5008. if (t.name === cur) opt.selected = true;
  5009. sel.appendChild(opt);
  5010. });
  5011. }
  5012. const routes = (state.routes || []).filter(r => !tableFilter || r.routing_table === tableFilter);
  5013. document.getElementById('routes-count-badge').innerText = `${routes.length} Routes`;
  5014. if (routes.length === 0) {
  5015. empty?.classList.remove('hidden');
  5016. return;
  5017. }
  5018. empty?.classList.add('hidden');
  5019. routes.forEach(r => {
  5020. const tr = document.createElement('tr');
  5021. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  5022. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  5023. // MikroTik Flags string: D=Dynamic, A=Active, C=Connect, S=Static, X=Disabled
  5024. let flags = '';
  5025. if (r.dynamic) flags += 'D';
  5026. if (r.active) flags += 'A';
  5027. if (r.connect) flags += 'C';
  5028. if (r.static) flags += 'S';
  5029. if (r.disabled) flags += 'X';
  5030. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  5031. tr.innerHTML = `
  5032. <td class="py-2.5 px-3 text-center">
  5033. <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'}">
  5034. ${flags || '-'}
  5035. </span>
  5036. </td>
  5037. <td class="py-2.5 px-3 font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${r.dst_address}</td>
  5038. <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>
  5039. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  5040. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  5041. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  5042. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  5043. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5044. ${r.static ? `
  5045. <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>
  5046. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  5047. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5048. ` : `
  5049. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  5050. `}
  5051. </td>
  5052. `;
  5053. tbody.appendChild(tr);
  5054. });
  5055. }
  5056. function openAddRouteModal() {
  5057. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  5058. document.getElementById('route-modal-id').value = '';
  5059. document.getElementById('route-modal-old-dst').value = '';
  5060. document.getElementById('route-modal-old-gw').value = '';
  5061. document.getElementById('route-modal-old-distance').value = '';
  5062. document.getElementById('route-modal-old-table').value = '';
  5063. document.getElementById('route-modal-old-iface').value = '';
  5064. const dstInput = document.getElementById('route-modal-dst');
  5065. const gwInput = document.getElementById('route-modal-gw');
  5066. const distInput = document.getElementById('route-modal-distance');
  5067. const ifaceSelect = document.getElementById('route-modal-iface');
  5068. const tableSelect = document.getElementById('route-modal-table');
  5069. const commentInput = document.getElementById('route-modal-comment');
  5070. const disCheck = document.getElementById('route-modal-disabled');
  5071. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  5072. dstInput.disabled = false;
  5073. dstInput.value = '0.0.0.0/0';
  5074. gwInput.disabled = false;
  5075. gwInput.value = '';
  5076. distInput.disabled = false;
  5077. distInput.value = '1';
  5078. ifaceSelect.disabled = false;
  5079. tableSelect.disabled = false;
  5080. commentInput.disabled = false;
  5081. commentInput.value = '';
  5082. disCheck.disabled = false;
  5083. disCheck.checked = false;
  5084. if (saveBtn) saveBtn.classList.remove('hidden');
  5085. populateInterfaceSelect('route-modal-iface');
  5086. // Populate tables
  5087. tableSelect.innerHTML = '';
  5088. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  5089. const opt = document.createElement('option');
  5090. opt.value = t.name;
  5091. opt.innerText = t.name;
  5092. if (t.name === 'main') opt.selected = true;
  5093. tableSelect.appendChild(opt);
  5094. });
  5095. document.getElementById('route-modal').classList.remove('hidden');
  5096. }
  5097. function openEditRouteModal(id) {
  5098. const r = (state.routes || []).find(route => route.id === id);
  5099. if (!r) return;
  5100. const isStatic = !!r.static;
  5101. document.getElementById('route-modal-title').innerText = isStatic
  5102. ? `Edit Route: ${r.dst_address}`
  5103. : `Route Properties (Read Only): ${r.dst_address}`;
  5104. document.getElementById('route-modal-id').value = r.id;
  5105. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  5106. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  5107. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  5108. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  5109. document.getElementById('route-modal-old-iface').value = r.interface || '';
  5110. const dstInput = document.getElementById('route-modal-dst');
  5111. const gwInput = document.getElementById('route-modal-gw');
  5112. const distInput = document.getElementById('route-modal-distance');
  5113. const ifaceSelect = document.getElementById('route-modal-iface');
  5114. const tableSelect = document.getElementById('route-modal-table');
  5115. const commentInput = document.getElementById('route-modal-comment');
  5116. const disCheck = document.getElementById('route-modal-disabled');
  5117. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  5118. dstInput.value = r.dst_address;
  5119. gwInput.value = r.gateway || '';
  5120. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  5121. commentInput.value = r.comment || '';
  5122. disCheck.checked = !!r.disabled;
  5123. dstInput.disabled = !isStatic;
  5124. gwInput.disabled = !isStatic;
  5125. distInput.disabled = !isStatic;
  5126. ifaceSelect.disabled = !isStatic;
  5127. tableSelect.disabled = !isStatic;
  5128. commentInput.disabled = !isStatic;
  5129. disCheck.disabled = !isStatic;
  5130. if (saveBtn) {
  5131. if (isStatic) {
  5132. saveBtn.classList.remove('hidden');
  5133. } else {
  5134. saveBtn.classList.add('hidden');
  5135. }
  5136. }
  5137. populateInterfaceSelect('route-modal-iface', r.interface);
  5138. tableSelect.innerHTML = '';
  5139. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  5140. const opt = document.createElement('option');
  5141. opt.value = t.name;
  5142. opt.innerText = t.name;
  5143. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  5144. tableSelect.appendChild(opt);
  5145. });
  5146. document.getElementById('route-modal').classList.remove('hidden');
  5147. }
  5148. function closeRouteModal() {
  5149. document.getElementById('route-modal').classList.add('hidden');
  5150. }
  5151. async function submitSaveRoute(e) {
  5152. e.preventDefault();
  5153. const id = document.getElementById('route-modal-id').value;
  5154. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  5155. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  5156. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  5157. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  5158. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  5159. const dst = document.getElementById('route-modal-dst').value.trim();
  5160. const gw = document.getElementById('route-modal-gw').value.trim();
  5161. const table = document.getElementById('route-modal-table').value;
  5162. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  5163. const iface = document.getElementById('route-modal-iface').value;
  5164. const comment = document.getElementById('route-modal-comment').value.trim();
  5165. const disabled = document.getElementById('route-modal-disabled').checked;
  5166. if (!dst) {
  5167. showToast('Error', 'Destination address is required', 'error');
  5168. return;
  5169. }
  5170. if (!gw && !iface) {
  5171. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  5172. return;
  5173. }
  5174. const payload = {
  5175. id,
  5176. old_dst_address: oldDst,
  5177. old_gateway: oldGw,
  5178. old_routing_table: oldTable,
  5179. old_interface: oldIface,
  5180. dst_address: dst,
  5181. gateway: gw || iface,
  5182. routing_table: table,
  5183. distance,
  5184. interface: iface,
  5185. comment,
  5186. disabled
  5187. };
  5188. if (oldDistStr !== undefined && oldDistStr !== '') {
  5189. payload.old_distance = parseInt(oldDistStr, 10);
  5190. }
  5191. try {
  5192. const res = await fetch(`${API_BASE}/routes`, {
  5193. method: 'POST',
  5194. headers: { 'Content-Type': 'application/json' },
  5195. body: JSON.stringify(payload)
  5196. });
  5197. if (res.ok) {
  5198. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  5199. closeRouteModal();
  5200. loadRoutes();
  5201. } else {
  5202. const err = await res.json();
  5203. showToast('Error', err.message || 'Failed to save route', 'error');
  5204. }
  5205. } catch (err) {
  5206. showToast('Error', err.message, 'error');
  5207. }
  5208. }
  5209. async function toggleRouteState(id, disabled) {
  5210. try {
  5211. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  5212. method: 'POST',
  5213. headers: { 'Content-Type': 'application/json' },
  5214. body: JSON.stringify({ disabled })
  5215. });
  5216. if (res.ok) loadRoutes();
  5217. } catch (err) {
  5218. showToast('Error', err.message, 'error');
  5219. }
  5220. }
  5221. async function deleteRoute(id) {
  5222. if (!confirm('Are you sure you want to delete this route?')) return;
  5223. try {
  5224. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5225. if (res.ok) {
  5226. showToast('Deleted', 'Route removed', 'success');
  5227. loadRoutes();
  5228. }
  5229. } catch (err) {
  5230. showToast('Error', err.message, 'error');
  5231. }
  5232. }
  5233. // ----------------- Policy Rules (/ip route rule) -----------------
  5234. function renderPolicyRules() {
  5235. const tbody = document.getElementById('rules-table-body');
  5236. const empty = document.getElementById('rules-empty');
  5237. if (!tbody) return;
  5238. tbody.innerHTML = '';
  5239. const showSystem = document.getElementById('prule-show-system')?.checked;
  5240. const filtered = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  5241. const countBadge = document.getElementById('rules-count-badge');
  5242. if (countBadge) countBadge.innerText = `${filtered.length} Rules`;
  5243. const bRules = document.getElementById('routes-badge-rules');
  5244. if (bRules) bRules.innerText = filtered.length;
  5245. if (filtered.length === 0) {
  5246. empty?.classList.remove('hidden');
  5247. return;
  5248. }
  5249. empty?.classList.add('hidden');
  5250. filtered.forEach(pr => {
  5251. const isSys = pr.is_default || pr.is_system;
  5252. const tr = document.createElement('tr');
  5253. tr.className = `hover:bg-slate-800/40 transition text-xs ${isSys ? 'opacity-70 bg-slate-950/20' : ''}`;
  5254. tr.innerHTML = `
  5255. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  5256. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  5257. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  5258. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  5259. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  5260. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  5261. <td class="py-2.5 px-3 text-right font-sans">
  5262. ${!pr.is_default ? `
  5263. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5264. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  5265. </td>
  5266. `;
  5267. tbody.appendChild(tr);
  5268. });
  5269. }
  5270. function openAddPolicyRuleModal() {
  5271. const userRules = (state.policyRules || []).filter(pr => !pr.is_default && !pr.is_system);
  5272. document.getElementById('prule-modal-pref').value = userRules.length * 10 + 1000;
  5273. document.getElementById('prule-modal-mark').value = '';
  5274. document.getElementById('prule-modal-src').value = '';
  5275. document.getElementById('prule-modal-dst').value = '';
  5276. const sel = document.getElementById('prule-modal-table');
  5277. sel.innerHTML = '';
  5278. (state.routingTables || []).forEach(t => {
  5279. const opt = document.createElement('option');
  5280. opt.value = t.name;
  5281. opt.innerText = t.name;
  5282. sel.appendChild(opt);
  5283. });
  5284. document.getElementById('prule-modal').classList.remove('hidden');
  5285. }
  5286. function closePolicyRuleModal() {
  5287. document.getElementById('prule-modal').classList.add('hidden');
  5288. }
  5289. async function submitSavePolicyRule(e) {
  5290. e.preventDefault();
  5291. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  5292. const mark = document.getElementById('prule-modal-mark').value.trim();
  5293. const src = document.getElementById('prule-modal-src').value.trim();
  5294. const dst = document.getElementById('prule-modal-dst').value.trim();
  5295. const table = document.getElementById('prule-modal-table').value;
  5296. const action = document.getElementById('prule-modal-action').value;
  5297. try {
  5298. const res = await fetch(`${API_BASE}/routing/rules`, {
  5299. method: 'POST',
  5300. headers: { 'Content-Type': 'application/json' },
  5301. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  5302. });
  5303. if (res.ok) {
  5304. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  5305. closePolicyRuleModal();
  5306. loadRoutes();
  5307. } else {
  5308. const err = await res.json();
  5309. showToast('Error', err.message, 'error');
  5310. }
  5311. } catch (err) {
  5312. showToast('Error', err.message, 'error');
  5313. }
  5314. }
  5315. async function deletePolicyRule(id) {
  5316. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  5317. try {
  5318. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5319. if (res.ok) {
  5320. showToast('Rule Removed', 'Policy rule deleted', 'success');
  5321. loadRoutes();
  5322. }
  5323. } catch (err) {
  5324. showToast('Error', err.message, 'error');
  5325. }
  5326. }
  5327. // ----------------- Routing Tables -----------------
  5328. function renderRoutingTables() {
  5329. const tbody = document.getElementById('tables-table-body');
  5330. if (!tbody) return;
  5331. tbody.innerHTML = '';
  5332. (state.routingTables || []).forEach(t => {
  5333. const tr = document.createElement('tr');
  5334. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  5335. tr.innerHTML = `
  5336. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  5337. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  5338. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  5339. `;
  5340. tbody.appendChild(tr);
  5341. });
  5342. }
  5343. function openAddTableModal() {
  5344. document.getElementById('table-modal-name').value = '';
  5345. document.getElementById('table-modal-id').value = '';
  5346. document.getElementById('table-modal-comment').value = '';
  5347. document.getElementById('table-modal').classList.remove('hidden');
  5348. }
  5349. function closeTableModal() {
  5350. document.getElementById('table-modal').classList.add('hidden');
  5351. }
  5352. async function submitSaveTable(e) {
  5353. e.preventDefault();
  5354. const name = document.getElementById('table-modal-name').value.trim();
  5355. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  5356. const comment = document.getElementById('table-modal-comment').value.trim();
  5357. try {
  5358. const res = await fetch(`${API_BASE}/routing/tables`, {
  5359. method: 'POST',
  5360. headers: { 'Content-Type': 'application/json' },
  5361. body: JSON.stringify({ name, table_id: id, comment })
  5362. });
  5363. if (res.ok) {
  5364. showToast('Table Created', `Routing table ${name} registered`, 'success');
  5365. closeTableModal();
  5366. loadRoutes();
  5367. } else {
  5368. const err = await res.json();
  5369. showToast('Error', err.message, 'error');
  5370. }
  5371. } catch (err) {
  5372. showToast('Error', err.message, 'error');
  5373. }
  5374. }
  5375. async function loadDebianConfig() {
  5376. const view = document.getElementById('debian-config-view');
  5377. view.innerText = 'Generating live configuration...';
  5378. try {
  5379. const res = await fetch(`${API_BASE}/debian/config`);
  5380. const data = await res.json();
  5381. view.innerText = data.content || '# Empty config';
  5382. } catch (err) {
  5383. view.innerText = 'Failed to generate Debian network config.';
  5384. }
  5385. }
  5386. async function saveDebianConfig() {
  5387. try {
  5388. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  5389. const data = await res.json();
  5390. if (res.ok) {
  5391. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  5392. loadDebianConfig();
  5393. }
  5394. } catch (err) {
  5395. showToast('Error', err.message, 'error');
  5396. }
  5397. }
  5398. function showToast(title, message, type = 'info') {
  5399. const container = document.getElementById('toast-container');
  5400. const toast = document.createElement('div');
  5401. const borderColors = {
  5402. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  5403. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  5404. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  5405. };
  5406. 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}`;
  5407. toast.innerHTML = `
  5408. <div class="flex-1">
  5409. <div class="font-bold text-xs text-white">${title}</div>
  5410. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${message}</div>
  5411. </div>
  5412. `;
  5413. container.appendChild(toast);
  5414. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  5415. setTimeout(() => {
  5416. toast.classList.add('opacity-0', 'translate-y-2');
  5417. setTimeout(() => toast.remove(), 300);
  5418. }, 4000);
  5419. }
  5420. function formatTraffic(bytesPerSec) {
  5421. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  5422. const kb = bytesPerSec / 1024;
  5423. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  5424. const mb = kb / 1024;
  5425. return `${mb.toFixed(2)} MB/s`;
  5426. }
  5427. function toggleSidebar() {
  5428. const sb = document.getElementById('sidebar');
  5429. sb.classList.toggle('-translate-x-full');
  5430. }
  5431. // ======================== EoIP (Ethernet over IP) ========================
  5432. async function loadEoIP(populate = true) {
  5433. try {
  5434. const res = await fetch(`${API_BASE}/vpn/eoip`);
  5435. const data = await res.json();
  5436. state.eoipTunnels = Array.isArray(data) ? data : [];
  5437. const badge = document.getElementById('eoip-count-badge');
  5438. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  5439. const sideBadge = document.getElementById('badge-eoip-count');
  5440. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  5441. renderEoIPTunnels();
  5442. } catch (err) {
  5443. console.error('Failed to load EoIP:', err);
  5444. }
  5445. }
  5446. function renderEoIPTunnels() {
  5447. const tbody = document.getElementById('eoip-table-body');
  5448. const empty = document.getElementById('eoip-empty');
  5449. if (!tbody) return;
  5450. tbody.innerHTML = '';
  5451. const tunnels = state.eoipTunnels || [];
  5452. if (tunnels.length === 0) {
  5453. empty?.classList.remove('hidden');
  5454. return;
  5455. }
  5456. empty?.classList.add('hidden');
  5457. tunnels.forEach(t => {
  5458. const tr = document.createElement('tr');
  5459. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  5460. tr.innerHTML = `
  5461. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  5462. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  5463. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  5464. <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>
  5465. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  5466. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  5467. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  5468. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  5469. <td class="py-2.5 px-3 font-mono text-[11px]">
  5470. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  5471. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  5472. </td>
  5473. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  5474. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  5475. <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>
  5476. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  5477. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  5478. </td>
  5479. `;
  5480. tbody.appendChild(tr);
  5481. });
  5482. }
  5483. function openAddEoIPModal() {
  5484. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  5485. document.getElementById('eoip-modal-id').value = '';
  5486. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  5487. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  5488. document.getElementById('eoip-modal-remote').value = '';
  5489. document.getElementById('eoip-modal-ip').value = '';
  5490. document.getElementById('eoip-modal-local').value = '';
  5491. document.getElementById('eoip-modal-mac').value = '';
  5492. document.getElementById('eoip-modal-mtu').value = '1500';
  5493. document.getElementById('eoip-modal-comment').value = '';
  5494. document.getElementById('eoip-modal-clampmss').checked = true;
  5495. document.getElementById('eoip-modal-disabled').checked = false;
  5496. document.getElementById('eoip-modal').classList.remove('hidden');
  5497. }
  5498. function openEditEoIPModal(id) {
  5499. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  5500. if (!t) return;
  5501. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  5502. document.getElementById('eoip-modal-id').value = t.id;
  5503. document.getElementById('eoip-modal-name').value = t.name;
  5504. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  5505. document.getElementById('eoip-modal-remote').value = t.remote_address;
  5506. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  5507. document.getElementById('eoip-modal-local').value = t.local_address || '';
  5508. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  5509. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  5510. document.getElementById('eoip-modal-comment').value = t.comment || '';
  5511. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  5512. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  5513. document.getElementById('eoip-modal').classList.remove('hidden');
  5514. }
  5515. function closeEoIPModal() {
  5516. document.getElementById('eoip-modal').classList.add('hidden');
  5517. }
  5518. async function submitSaveEoIP(e) {
  5519. e.preventDefault();
  5520. const id = document.getElementById('eoip-modal-id').value;
  5521. const name = document.getElementById('eoip-modal-name').value.trim();
  5522. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  5523. const remote = document.getElementById('eoip-modal-remote').value.trim();
  5524. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  5525. const local = document.getElementById('eoip-modal-local').value.trim();
  5526. const mac = document.getElementById('eoip-modal-mac').value.trim();
  5527. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  5528. const comment = document.getElementById('eoip-modal-comment').value.trim();
  5529. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  5530. const disabled = document.getElementById('eoip-modal-disabled').checked;
  5531. try {
  5532. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  5533. method: 'POST',
  5534. headers: { 'Content-Type': 'application/json' },
  5535. body: JSON.stringify({
  5536. id,
  5537. name,
  5538. tunnel_id: tunnelId,
  5539. remote_address: remote,
  5540. ip_address: ipAddress,
  5541. local_address: local,
  5542. mac_address: mac,
  5543. mtu,
  5544. clamp_mss: clampMss,
  5545. comment,
  5546. disabled
  5547. })
  5548. });
  5549. if (res.ok) {
  5550. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  5551. closeEoIPModal();
  5552. loadEoIP(false);
  5553. fetchData(false);
  5554. } else {
  5555. const err = await res.json();
  5556. showToast('Error', err.message, 'error');
  5557. }
  5558. } catch (err) {
  5559. showToast('Error', err.message, 'error');
  5560. }
  5561. }
  5562. async function toggleEoIPState(id, disabled) {
  5563. try {
  5564. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  5565. method: 'POST',
  5566. headers: { 'Content-Type': 'application/json' },
  5567. body: JSON.stringify({ disabled })
  5568. });
  5569. if (res.ok) {
  5570. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  5571. loadEoIP(false);
  5572. fetchData(false);
  5573. }
  5574. } catch (err) {
  5575. showToast('Error', err.message, 'error');
  5576. }
  5577. }
  5578. async function deleteEoIP(id) {
  5579. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  5580. try {
  5581. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5582. if (res.ok) {
  5583. showToast('Deleted', 'EoIP tunnel removed', 'success');
  5584. loadEoIP(false);
  5585. fetchData(false);
  5586. }
  5587. } catch (err) {
  5588. showToast('Error', err.message, 'error');
  5589. }
  5590. }
  5591. // ======================== PPP Central Hub & Servers ========================
  5592. function switchPPPSubTab(tab) {
  5593. state.pppSubTab = tab;
  5594. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  5595. tabs.forEach(t => {
  5596. const panel = document.getElementById(`ppp-subtab-${t}`);
  5597. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  5598. if (panel) {
  5599. if (t === tab) panel.classList.remove('hidden');
  5600. else panel.classList.add('hidden');
  5601. }
  5602. if (btn) {
  5603. if (t === tab) {
  5604. 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';
  5605. } else {
  5606. 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';
  5607. }
  5608. }
  5609. });
  5610. const addBtn = document.getElementById('ppp-primary-add-btn');
  5611. if (addBtn) {
  5612. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  5613. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  5614. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  5615. else addBtn.innerHTML = '<span>Save Config</span>';
  5616. }
  5617. if (tab === 'active') loadPPPSessions();
  5618. }
  5619. function openCurrentPPPModal() {
  5620. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  5621. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  5622. else if (state.pppSubTab === 'active') loadPPPSessions();
  5623. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  5624. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  5625. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  5626. }
  5627. async function loadPPP(populateDropdowns = true) {
  5628. await Promise.all([
  5629. loadPPPSecrets(),
  5630. loadPPPProfiles(),
  5631. loadPPPServers(),
  5632. loadPPPSessions()
  5633. ]);
  5634. }
  5635. async function loadPPPSecrets() {
  5636. try {
  5637. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  5638. const data = await res.json();
  5639. state.pppSecrets = Array.isArray(data) ? data : [];
  5640. const b = document.getElementById('ppp-badge-secrets');
  5641. if (b) b.innerText = state.pppSecrets.length;
  5642. const b2 = document.getElementById('secrets-count-badge');
  5643. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  5644. renderPPPSecrets();
  5645. } catch (err) {
  5646. console.error('Failed to load PPP secrets:', err);
  5647. }
  5648. }
  5649. function renderPPPSecrets() {
  5650. const tbody = document.getElementById('secrets-table-body');
  5651. const empty = document.getElementById('secrets-empty');
  5652. if (!tbody) return;
  5653. tbody.innerHTML = '';
  5654. const secrets = state.pppSecrets || [];
  5655. if (secrets.length === 0) {
  5656. empty?.classList.remove('hidden');
  5657. return;
  5658. }
  5659. empty?.classList.add('hidden');
  5660. secrets.forEach(s => {
  5661. const tr = document.createElement('tr');
  5662. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  5663. tr.innerHTML = `
  5664. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  5665. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  5666. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  5667. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  5668. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  5669. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  5670. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  5671. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  5672. <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>
  5673. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  5674. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  5675. </td>
  5676. `;
  5677. tbody.appendChild(tr);
  5678. });
  5679. }
  5680. async function loadPPPProfiles() {
  5681. try {
  5682. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  5683. const data = await res.json();
  5684. state.pppProfiles = Array.isArray(data) ? data : [];
  5685. const b = document.getElementById('ppp-badge-profiles');
  5686. if (b) b.innerText = state.pppProfiles.length;
  5687. const b2 = document.getElementById('profiles-count-badge');
  5688. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  5689. // Populate profile selects across modals
  5690. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  5691. selects.forEach(sid => {
  5692. const el = document.getElementById(sid);
  5693. if (!el) return;
  5694. const cur = el.value;
  5695. el.innerHTML = '';
  5696. state.pppProfiles.forEach(p => {
  5697. const opt = document.createElement('option');
  5698. opt.value = p.name;
  5699. opt.innerText = `${p.name} (${p.remote_address})`;
  5700. if (p.name === cur) opt.selected = true;
  5701. el.appendChild(opt);
  5702. });
  5703. });
  5704. renderPPPProfiles();
  5705. } catch (err) {
  5706. console.error('Failed to load PPP profiles:', err);
  5707. }
  5708. }
  5709. function renderPPPProfiles() {
  5710. const tbody = document.getElementById('profiles-table-body');
  5711. if (!tbody) return;
  5712. tbody.innerHTML = '';
  5713. (state.pppProfiles || []).forEach(p => {
  5714. const isDefault = p.name.startsWith('default');
  5715. const tr = document.createElement('tr');
  5716. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  5717. tr.innerHTML = `
  5718. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  5719. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  5720. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  5721. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  5722. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  5723. <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>
  5724. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  5725. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  5726. ${!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>`}
  5727. </td>
  5728. `;
  5729. tbody.appendChild(tr);
  5730. });
  5731. }
  5732. async function loadPPPServers() {
  5733. try {
  5734. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  5735. fetch(`${API_BASE}/vpn/servers/pppoe`),
  5736. fetch(`${API_BASE}/vpn/servers/pptp`),
  5737. fetch(`${API_BASE}/vpn/servers/l2tp`),
  5738. fetch(`${API_BASE}/vpn/servers/ipsec`)
  5739. ]);
  5740. if (pppoeRes.ok) {
  5741. state.pppoeServer = await pppoeRes.json();
  5742. const s = state.pppoeServer;
  5743. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  5744. document.getElementById('pppoe-server-name').value = s.service_name || 'proxmox-pppoe';
  5745. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  5746. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  5747. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  5748. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  5749. const pill = document.getElementById('pppoe-server-status-pill');
  5750. if (pill) {
  5751. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  5752. 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';
  5753. }
  5754. setDotBadge('ppp-badge-pppoe-state', s.running);
  5755. }
  5756. if (pptpRes.ok) {
  5757. state.pptpServer = await pptpRes.json();
  5758. const s = state.pptpServer;
  5759. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  5760. document.getElementById('pptp-server-port').value = s.port || 1723;
  5761. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  5762. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  5763. const pill = document.getElementById('pptp-server-status-pill');
  5764. if (pill) {
  5765. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  5766. 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';
  5767. }
  5768. setDotBadge('ppp-badge-pptp-state', s.running);
  5769. }
  5770. if (l2tpRes.ok) {
  5771. state.l2tpServer = await l2tpRes.json();
  5772. const s = state.l2tpServer;
  5773. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  5774. document.getElementById('l2tp-server-port').value = s.port || 1701;
  5775. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  5776. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  5777. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  5778. const pill = document.getElementById('l2tp-server-status-pill');
  5779. if (pill) {
  5780. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  5781. 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';
  5782. }
  5783. setDotBadge('ppp-badge-l2tp-state', s.running);
  5784. }
  5785. if (ipsecRes.ok) {
  5786. state.ipsecServer = await ipsecRes.json();
  5787. const s = state.ipsecServer;
  5788. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  5789. if (modalEn) modalEn.checked = !!s.enabled;
  5790. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  5791. if (modalPsk) modalPsk.value = s.preshared_key || '';
  5792. const modalPool = document.getElementById('modal-ipsec-server-pool');
  5793. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  5794. const modalDns = document.getElementById('modal-ipsec-server-dns');
  5795. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  5796. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  5797. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  5798. const pill = document.getElementById('modal-ipsec-server-status');
  5799. if (pill) {
  5800. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  5801. 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';
  5802. }
  5803. }
  5804. } catch (err) {
  5805. console.error('Failed to load VPN servers:', err);
  5806. }
  5807. }
  5808. async function loadPPPSessions() {
  5809. try {
  5810. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  5811. const data = await res.json();
  5812. state.pppActiveSessions = Array.isArray(data) ? data : [];
  5813. const b = document.getElementById('ppp-badge-active');
  5814. if (b) b.innerText = state.pppActiveSessions.length;
  5815. const sideB = document.getElementById('badge-ppp-sessions');
  5816. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  5817. renderPPPSessions();
  5818. } catch (err) {
  5819. console.error('Failed to load active PPP sessions:', err);
  5820. }
  5821. }
  5822. function renderPPPSessions() {
  5823. const tbody = document.getElementById('active-ppp-table-body');
  5824. const empty = document.getElementById('active-ppp-empty');
  5825. if (!tbody) return;
  5826. tbody.innerHTML = '';
  5827. const list = state.pppActiveSessions || [];
  5828. if (list.length === 0) {
  5829. empty?.classList.remove('hidden');
  5830. return;
  5831. }
  5832. empty?.classList.add('hidden');
  5833. list.forEach(s => {
  5834. const tr = document.createElement('tr');
  5835. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  5836. tr.innerHTML = `
  5837. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  5838. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  5839. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  5840. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  5841. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  5842. <td class="py-2.5 px-3 text-[11px]">
  5843. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  5844. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  5845. </td>
  5846. <td class="py-2.5 px-3 text-right font-sans">
  5847. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  5848. </td>
  5849. `;
  5850. tbody.appendChild(tr);
  5851. });
  5852. }
  5853. async function disconnectPPPSession(iface) {
  5854. if (!confirm(`Disconnect session ${iface}?`)) return;
  5855. try {
  5856. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  5857. if (res.ok) {
  5858. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  5859. loadPPPSessions();
  5860. }
  5861. } catch (err) {
  5862. showToast('Error', err.message, 'error');
  5863. }
  5864. }
  5865. // PPP Secret Modal handlers
  5866. function openAddPPPSecretModal() {
  5867. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  5868. document.getElementById('secret-modal-id').value = '';
  5869. document.getElementById('secret-modal-name').value = '';
  5870. document.getElementById('secret-modal-password').value = '';
  5871. document.getElementById('secret-modal-service').value = 'any';
  5872. document.getElementById('secret-modal-profile').value = 'default';
  5873. document.getElementById('secret-modal-local').value = '';
  5874. document.getElementById('secret-modal-remote').value = '';
  5875. document.getElementById('secret-modal-comment').value = '';
  5876. document.getElementById('secret-modal-disabled').checked = false;
  5877. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  5878. }
  5879. function openEditPPPSecretModal(id) {
  5880. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  5881. if (!s) return;
  5882. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  5883. document.getElementById('secret-modal-id').value = s.id;
  5884. document.getElementById('secret-modal-name').value = s.name;
  5885. document.getElementById('secret-modal-password').value = s.password;
  5886. document.getElementById('secret-modal-service').value = s.service || 'any';
  5887. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  5888. document.getElementById('secret-modal-local').value = s.local_address || '';
  5889. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  5890. document.getElementById('secret-modal-comment').value = s.comment || '';
  5891. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  5892. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  5893. }
  5894. function closePPPSecretModal() {
  5895. document.getElementById('ppp-secret-modal').classList.add('hidden');
  5896. }
  5897. async function submitSavePPPSecret(e) {
  5898. e.preventDefault();
  5899. const id = document.getElementById('secret-modal-id').value;
  5900. const name = document.getElementById('secret-modal-name').value.trim();
  5901. const password = document.getElementById('secret-modal-password').value.trim();
  5902. const service = document.getElementById('secret-modal-service').value;
  5903. const profile = document.getElementById('secret-modal-profile').value;
  5904. const local = document.getElementById('secret-modal-local').value.trim();
  5905. const remote = document.getElementById('secret-modal-remote').value.trim();
  5906. const comment = document.getElementById('secret-modal-comment').value.trim();
  5907. const disabled = document.getElementById('secret-modal-disabled').checked;
  5908. try {
  5909. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  5910. method: 'POST',
  5911. headers: { 'Content-Type': 'application/json' },
  5912. body: JSON.stringify({
  5913. id,
  5914. name,
  5915. password,
  5916. service,
  5917. profile,
  5918. local_address: local,
  5919. remote_address: remote,
  5920. comment,
  5921. disabled
  5922. })
  5923. });
  5924. if (res.ok) {
  5925. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  5926. closePPPSecretModal();
  5927. loadPPPSecrets();
  5928. } else {
  5929. const err = await res.json();
  5930. showToast('Error', err.message, 'error');
  5931. }
  5932. } catch (err) {
  5933. showToast('Error', err.message, 'error');
  5934. }
  5935. }
  5936. async function togglePPPSecretState(id, disabled) {
  5937. try {
  5938. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  5939. method: 'POST',
  5940. headers: { 'Content-Type': 'application/json' },
  5941. body: JSON.stringify({ disabled })
  5942. });
  5943. if (res.ok) {
  5944. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  5945. loadPPPSecrets();
  5946. }
  5947. } catch (err) {
  5948. showToast('Error', err.message, 'error');
  5949. }
  5950. }
  5951. async function deletePPPSecret(id) {
  5952. if (!confirm('Are you sure you want to delete this secret account?')) return;
  5953. try {
  5954. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5955. if (res.ok) {
  5956. showToast('Deleted', 'Secret account removed', 'success');
  5957. loadPPPSecrets();
  5958. }
  5959. } catch (err) {
  5960. showToast('Error', err.message, 'error');
  5961. }
  5962. }
  5963. // PPP Profile Modal handlers
  5964. function openAddPPPProfileModal() {
  5965. document.getElementById('profile-modal-name').value = '';
  5966. document.getElementById('profile-modal-local').value = '10.10.10.1';
  5967. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  5968. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  5969. document.getElementById('profile-modal-encryption').value = 'required';
  5970. document.getElementById('profile-modal-onlyone').checked = true;
  5971. document.getElementById('profile-modal-comment').value = '';
  5972. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  5973. }
  5974. function closePPPProfileModal() {
  5975. document.getElementById('ppp-profile-modal').classList.add('hidden');
  5976. }
  5977. async function submitSavePPPProfile(e) {
  5978. e.preventDefault();
  5979. const name = document.getElementById('profile-modal-name').value.trim();
  5980. const local = document.getElementById('profile-modal-local').value.trim();
  5981. const remote = document.getElementById('profile-modal-remote').value.trim();
  5982. const dns = document.getElementById('profile-modal-dns').value.trim();
  5983. const enc = document.getElementById('profile-modal-encryption').value;
  5984. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  5985. const comment = document.getElementById('profile-modal-comment').value.trim();
  5986. try {
  5987. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  5988. method: 'POST',
  5989. headers: { 'Content-Type': 'application/json' },
  5990. body: JSON.stringify({
  5991. id: name,
  5992. name,
  5993. local_address: local,
  5994. remote_address: remote,
  5995. dns_servers: dns,
  5996. use_encryption: enc,
  5997. only_one: onlyone,
  5998. comment
  5999. })
  6000. });
  6001. if (res.ok) {
  6002. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  6003. closePPPProfileModal();
  6004. loadPPPProfiles();
  6005. } else {
  6006. const err = await res.json();
  6007. showToast('Error', err.message, 'error');
  6008. }
  6009. } catch (err) {
  6010. showToast('Error', err.message, 'error');
  6011. }
  6012. }
  6013. async function deletePPPProfile(name) {
  6014. if (!confirm(`Delete PPP profile ${name}?`)) return;
  6015. try {
  6016. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  6017. if (res.ok) {
  6018. showToast('Deleted', 'Profile removed', 'success');
  6019. loadPPPProfiles();
  6020. } else {
  6021. const err = await res.json();
  6022. showToast('Error', err.message, 'error');
  6023. }
  6024. } catch (err) {
  6025. showToast('Error', err.message, 'error');
  6026. }
  6027. }
  6028. // Server Config submissions
  6029. async function savePPPoEServerConfig(e) {
  6030. e.preventDefault();
  6031. const enabled = document.getElementById('pppoe-server-enabled').checked;
  6032. const name = document.getElementById('pppoe-server-name').value.trim();
  6033. const iface = document.getElementById('pppoe-server-iface').value;
  6034. const profile = document.getElementById('pppoe-server-profile').value;
  6035. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  6036. const onesession = document.getElementById('pppoe-server-onesession').checked;
  6037. try {
  6038. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  6039. method: 'POST',
  6040. headers: { 'Content-Type': 'application/json' },
  6041. body: JSON.stringify({
  6042. enabled,
  6043. service_name: name,
  6044. interface: iface,
  6045. default_profile: profile,
  6046. max_mtu: mtu,
  6047. max_mru: mtu,
  6048. one_session_per_host: onesession
  6049. })
  6050. });
  6051. if (res.ok) {
  6052. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  6053. loadPPPServers();
  6054. fetchData(false);
  6055. } else {
  6056. const err = await res.json();
  6057. showToast('Error', err.message, 'error');
  6058. }
  6059. } catch (err) {
  6060. showToast('Error', err.message, 'error');
  6061. }
  6062. }
  6063. async function savePPTPServerConfig(e) {
  6064. e.preventDefault();
  6065. const enabled = document.getElementById('pptp-server-enabled').checked;
  6066. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  6067. const profile = document.getElementById('pptp-server-profile').value;
  6068. const mppe = document.getElementById('pptp-server-mppe').checked;
  6069. try {
  6070. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  6071. method: 'POST',
  6072. headers: { 'Content-Type': 'application/json' },
  6073. body: JSON.stringify({
  6074. enabled,
  6075. port,
  6076. default_profile: profile,
  6077. require_mppe: mppe
  6078. })
  6079. });
  6080. if (res.ok) {
  6081. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  6082. loadPPPServers();
  6083. fetchData(false);
  6084. } else {
  6085. const err = await res.json();
  6086. showToast('Error', err.message, 'error');
  6087. }
  6088. } catch (err) {
  6089. showToast('Error', err.message, 'error');
  6090. }
  6091. }
  6092. async function saveL2TPServerConfig(e) {
  6093. e.preventDefault();
  6094. const enabled = document.getElementById('l2tp-server-enabled').checked;
  6095. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  6096. const profile = document.getElementById('l2tp-server-profile').value;
  6097. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  6098. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  6099. try {
  6100. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  6101. method: 'POST',
  6102. headers: { 'Content-Type': 'application/json' },
  6103. body: JSON.stringify({
  6104. enabled,
  6105. port,
  6106. default_profile: profile,
  6107. use_ipsec: useipsec,
  6108. ipsec_secret: psk
  6109. })
  6110. });
  6111. if (res.ok) {
  6112. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  6113. loadPPPServers();
  6114. fetchData(false);
  6115. } else {
  6116. const err = await res.json();
  6117. showToast('Error', err.message, 'error');
  6118. }
  6119. } catch (err) {
  6120. showToast('Error', err.message, 'error');
  6121. }
  6122. }
  6123. // IPSec Server Modal
  6124. function openIPSecServerModal() {
  6125. loadPPPServers();
  6126. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  6127. }
  6128. function closeIPSecServerModal() {
  6129. document.getElementById('ipsec-server-modal').classList.add('hidden');
  6130. }
  6131. async function submitSaveIPSecServer(e) {
  6132. e.preventDefault();
  6133. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  6134. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  6135. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  6136. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  6137. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  6138. try {
  6139. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  6140. method: 'POST',
  6141. headers: { 'Content-Type': 'application/json' },
  6142. body: JSON.stringify({
  6143. enabled,
  6144. preshared_key: psk,
  6145. pool_address: pool,
  6146. dns_servers: dns,
  6147. local_subnet: subnet
  6148. })
  6149. });
  6150. if (res.ok) {
  6151. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  6152. closeIPSecServerModal();
  6153. loadPPPServers();
  6154. fetchData(false);
  6155. } else {
  6156. const err = await res.json();
  6157. showToast('Error', err.message, 'error');
  6158. }
  6159. } catch (err) {
  6160. showToast('Error', err.message, 'error');
  6161. }
  6162. }
  6163. // WireGuard Client Config Viewer
  6164. let currentWGClientConf = '';
  6165. async function openWGClientConfModal(iface, clientIP) {
  6166. try {
  6167. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  6168. method: 'POST',
  6169. headers: { 'Content-Type': 'application/json' },
  6170. body: JSON.stringify({
  6171. interface: iface,
  6172. address: clientIP || '10.10.0.2/32',
  6173. dns: '1.1.1.1, 8.8.8.8'
  6174. })
  6175. });
  6176. if (res.ok) {
  6177. const data = await res.json();
  6178. currentWGClientConf = data.config;
  6179. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  6180. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  6181. } else {
  6182. const err = await res.json();
  6183. showToast('Error', err.message, 'error');
  6184. }
  6185. } catch (err) {
  6186. showToast('Error', err.message, 'error');
  6187. }
  6188. }
  6189. function closeWGClientConfModal() {
  6190. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  6191. }
  6192. function copyWGClientConf() {
  6193. if (!currentWGClientConf) return;
  6194. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  6195. }
  6196. function downloadWGClientConf() {
  6197. if (!currentWGClientConf) return;
  6198. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  6199. const a = document.createElement('a');
  6200. a.href = URL.createObjectURL(blob);
  6201. a.download = 'wireguard-client.conf';
  6202. document.body.appendChild(a);
  6203. a.click();
  6204. document.body.removeChild(a);
  6205. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  6206. }
  6207. // =========================================================================
  6208. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  6209. // =========================================================================
  6210. state.activeDynSubTab = 'bgp-peers';
  6211. state.activeBgpSubTab = 'bgp-peers';
  6212. state.activeOspfTab = 'instances';
  6213. state.bgpInstance = null;
  6214. state.bgpPeers = [];
  6215. state.bgpNets = [];
  6216. state.bgpRoutes = [];
  6217. state.ospfInstance = null;
  6218. state.ospfInstances = [];
  6219. state.ospfAreas = [];
  6220. state.ospfAreaRanges = [];
  6221. state.ospfTemplates = [];
  6222. state.ospfLiveInterfaces = [];
  6223. state.ospfStaticNbrs = [];
  6224. state.ospfNeighbors = [];
  6225. state.ospfLSA = [];
  6226. state.ospfRoutes = [];
  6227. state.selectedOspfRow = {
  6228. instances: null,
  6229. areas: null,
  6230. 'area-ranges': null,
  6231. templates: null,
  6232. interfaces: null,
  6233. 'static-nbrs': null,
  6234. neighbors: null,
  6235. lsa: null,
  6236. };
  6237. state.ospfSort = {
  6238. instances: { col: 'name', asc: true },
  6239. areas: { col: 'name', asc: true },
  6240. ranges: { col: 'area', asc: true },
  6241. templates: { col: 'interfaces', asc: true },
  6242. live_ifaces: { col: 'interface', asc: true },
  6243. snbrs: { col: 'address', asc: true },
  6244. neighbors: { col: 'address', asc: true },
  6245. lsa: { col: 'instance', asc: true },
  6246. };
  6247. function switchBgpSubTab(subTab) {
  6248. state.activeBgpSubTab = subTab;
  6249. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes'];
  6250. tabs.forEach(t => {
  6251. const el = document.getElementById(`dyn-subtab-${t}`);
  6252. const btn = document.getElementById(`bgp-subtab-btn-${t}`);
  6253. if (el) el.classList.toggle('hidden', t !== subTab);
  6254. if (btn) {
  6255. if (t === subTab) {
  6256. 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';
  6257. } else {
  6258. 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';
  6259. }
  6260. }
  6261. });
  6262. }
  6263. function switchOspfTab(tabName) {
  6264. state.activeOspfTab = tabName;
  6265. const tabs = ['instances', 'areas', 'area-ranges', 'templates', 'interfaces', 'static-nbrs', 'neighbors', 'lsa'];
  6266. tabs.forEach(t => {
  6267. const pane = document.getElementById(`ospf-pane-${t}`);
  6268. const btn = document.getElementById(`ospf-tab-btn-${t}`);
  6269. if (pane) pane.classList.toggle('hidden', t !== tabName);
  6270. if (btn) {
  6271. if (t === tabName) {
  6272. btn.className = 'px-3 py-2 text-xs font-semibold border-b-2 border-sky-500 text-white transition flex items-center gap-1.5 whitespace-nowrap';
  6273. } else {
  6274. btn.className = 'px-3 py-2 text-xs font-semibold border-b-2 border-transparent text-slate-400 hover:text-white transition flex items-center gap-1.5 whitespace-nowrap';
  6275. }
  6276. }
  6277. });
  6278. }
  6279. function switchOspfSubTab(tab) {
  6280. // Legacy alias
  6281. if (tab === 'ospf-ifaces') switchOspfTab('templates');
  6282. else if (tab === 'ospf-areas') switchOspfTab('areas');
  6283. else if (tab === 'ospf-nbrs') switchOspfTab('neighbors');
  6284. else switchOspfTab('instances');
  6285. }
  6286. function switchDynSubTab(subTab) {
  6287. if (subTab.startsWith('bgp')) {
  6288. if (state.activeTab !== 'bgp') navigate('bgp');
  6289. switchBgpSubTab(subTab);
  6290. } else if (subTab.startsWith('ospf')) {
  6291. if (state.activeTab !== 'ospf') navigate('ospf');
  6292. switchOspfTab('instances');
  6293. }
  6294. }
  6295. async function loadDynamicRouting(showToastMsg = false) {
  6296. try {
  6297. const fetchSafeJson = async (url) => {
  6298. try {
  6299. const r = await fetch(url);
  6300. return r.ok ? await r.json() : null;
  6301. } catch (e) {
  6302. return null;
  6303. }
  6304. };
  6305. const [
  6306. sum, bgpInst, bgpPeers, bgpNets, bgpRoutes,
  6307. ospfInsts, ospfAreas, ospfRanges, ospfTemplates, ospfLiveIfaces, ospfStaticNbrs, ospfNbrs, ospfLsa, filters,
  6308. selectRules, commLists, asLists
  6309. ] = await Promise.all([
  6310. fetchSafeJson(`${API_BASE}/routing/dynamic/summary`),
  6311. fetchSafeJson(`${API_BASE}/routing/bgp/instance`),
  6312. fetchSafeJson(`${API_BASE}/routing/bgp/peers`),
  6313. fetchSafeJson(`${API_BASE}/routing/bgp/networks`),
  6314. fetchSafeJson(`${API_BASE}/routing/bgp/routes`),
  6315. fetchSafeJson(`${API_BASE}/routing/ospf/instances`),
  6316. fetchSafeJson(`${API_BASE}/routing/ospf/areas`),
  6317. fetchSafeJson(`${API_BASE}/routing/ospf/area-ranges`),
  6318. fetchSafeJson(`${API_BASE}/routing/ospf/templates`),
  6319. fetchSafeJson(`${API_BASE}/routing/ospf/interfaces-live`),
  6320. fetchSafeJson(`${API_BASE}/routing/ospf/static-neighbors`),
  6321. fetchSafeJson(`${API_BASE}/routing/ospf/neighbors`),
  6322. fetchSafeJson(`${API_BASE}/routing/ospf/lsa`),
  6323. fetchSafeJson(`${API_BASE}/routing/filters`),
  6324. fetchSafeJson(`${API_BASE}/routing/filters/select-rules`),
  6325. fetchSafeJson(`${API_BASE}/routing/filters/community-lists`),
  6326. fetchSafeJson(`${API_BASE}/routing/filters/as-lists`)
  6327. ]);
  6328. if (sum) state.dynSummary = sum;
  6329. if (bgpInst) state.bgpInstance = bgpInst;
  6330. if (bgpPeers) state.bgpPeers = bgpPeers;
  6331. if (bgpNets) state.bgpNets = bgpNets;
  6332. if (bgpRoutes) state.bgpRoutes = bgpRoutes;
  6333. if (ospfInsts) state.ospfInstances = ospfInsts;
  6334. if (ospfAreas) state.ospfAreas = ospfAreas;
  6335. if (ospfRanges) state.ospfAreaRanges = ospfRanges;
  6336. if (ospfTemplates) state.ospfTemplates = ospfTemplates;
  6337. if (ospfLiveIfaces) state.ospfLiveInterfaces = ospfLiveIfaces;
  6338. if (ospfStaticNbrs) state.ospfStaticNbrs = ospfStaticNbrs;
  6339. if (ospfNbrs) state.ospfNeighbors = ospfNbrs;
  6340. if (ospfLsa) state.ospfLSA = ospfLsa;
  6341. if (filters) state.routingFilters = filters;
  6342. if (selectRules) state.routingSelectRules = selectRules;
  6343. if (commLists) state.routingCommunityLists = commLists;
  6344. if (asLists) state.routingASLists = asLists;
  6345. try { renderBgpStatusPill(); } catch(e) { console.error('renderBgpStatusPill error:', e); }
  6346. try { renderBgpPeers(); } catch(e) { console.error('renderBgpPeers error:', e); }
  6347. try { renderBgpNetworks(); } catch(e) { console.error('renderBgpNetworks error:', e); }
  6348. try { renderBgpRoutes(); } catch(e) { console.error('renderBgpRoutes error:', e); }
  6349. try { renderOspfInstances(); } catch(e) { console.error('renderOspfInstances error:', e); }
  6350. try { renderOspfAreas(); } catch(e) { console.error('renderOspfAreas error:', e); }
  6351. try { renderOspfAreaRanges(); } catch(e) { console.error('renderOspfAreaRanges error:', e); }
  6352. try { renderOspfTemplates(); } catch(e) { console.error('renderOspfTemplates error:', e); }
  6353. try { renderOspfLiveInterfaces(); } catch(e) { console.error('renderOspfLiveInterfaces error:', e); }
  6354. try { renderOspfStaticNbrs(); } catch(e) { console.error('renderOspfStaticNbrs error:', e); }
  6355. try { renderOspfNeighbors(); } catch(e) { console.error('renderOspfNeighbors error:', e); }
  6356. try { renderOspfLSA(); } catch(e) { console.error('renderOspfLSA error:', e); }
  6357. try { renderRoutingFilters(); } catch(e) { console.error('renderRoutingFilters error:', e); }
  6358. try { updateBadges(); } catch(e) { console.error('updateBadges error:', e); }
  6359. if (showToastMsg) showToast('Refreshed', 'Dynamic routing telemetry updated', 'info');
  6360. } catch (err) {
  6361. console.error('Failed to load dynamic routing:', err);
  6362. if (showToastMsg) showToast('Notice', 'Unable to refresh dynamic routing telemetry', 'warning');
  6363. }
  6364. }
  6365. async function loadOspfAll() {
  6366. await loadDynamicRouting(true);
  6367. }
  6368. function renderBgpStatusPill() {
  6369. const pill = document.getElementById('bgp-live-status-pill');
  6370. if (!pill) return;
  6371. const inst = state.bgpInstance;
  6372. if (!inst || !inst.enabled) {
  6373. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  6374. pill.innerText = 'BGP DISABLED';
  6375. } else if (inst.running) {
  6376. 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';
  6377. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  6378. } else {
  6379. 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';
  6380. pill.innerText = 'BGP STARTING...';
  6381. }
  6382. }
  6383. function renderBgpPeers() {
  6384. const tbody = document.getElementById('bgp-peers-table-body');
  6385. if (!tbody) return;
  6386. const empty = document.getElementById('bgp-peers-empty');
  6387. const countBadge = document.getElementById('bgp-peers-count-badge');
  6388. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  6389. const peers = state.bgpPeers || [];
  6390. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  6391. if (navBadge) navBadge.innerText = peers.length;
  6392. if (peers.length === 0) {
  6393. tbody.innerHTML = '';
  6394. if (empty) empty.classList.remove('hidden');
  6395. return;
  6396. }
  6397. if (empty) empty.classList.add('hidden');
  6398. tbody.innerHTML = peers.map(p => {
  6399. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  6400. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  6401. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  6402. let stateBadge = '';
  6403. if (p.disabled) {
  6404. 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>';
  6405. } else if (p.state === 'Established') {
  6406. 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>';
  6407. } else if (p.state === 'Connect' || p.state === 'Active') {
  6408. 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>`;
  6409. } else {
  6410. 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>`;
  6411. }
  6412. return `
  6413. <tr class="hover:bg-slate-800/40 transition">
  6414. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  6415. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  6416. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  6417. <td class="py-2.5 px-3">
  6418. <div class="font-bold text-slate-200">AS ${p.remote_as}</div>
  6419. ${p.local_as ? `<div class="text-[10px] text-purple-400 font-mono font-semibold" title="Custom Multi-Instance AS">Local: AS ${p.local_as}</div>` : `<div class="text-[10px] text-slate-500 font-mono">Global AS</div>`}
  6420. </td>
  6421. <td class="py-2.5 px-3">${stateBadge}</td>
  6422. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  6423. <td class="py-2.5 px-3 text-slate-300">
  6424. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  6425. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  6426. </td>
  6427. <td class="py-2.5 px-3 font-mono text-[11px] whitespace-nowrap">
  6428. ${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> ` : ''}
  6429. ${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>` : ''}
  6430. ${!p.in_filter && !p.out_filter ? '<span class="text-slate-600">-</span>' : ''}
  6431. </td>
  6432. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  6433. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  6434. <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'}">
  6435. ${p.disabled ? 'Enable' : 'Disable'}
  6436. </button>
  6437. <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">
  6438. Edit
  6439. </button>
  6440. <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">
  6441. Delete
  6442. </button>
  6443. </td>
  6444. </tr>
  6445. `;
  6446. }).join('');
  6447. }
  6448. function renderBgpNetworks() {
  6449. const tbody = document.getElementById('bgp-nets-table-body');
  6450. if (!tbody) return;
  6451. const empty = document.getElementById('bgp-nets-empty');
  6452. const countBadge = document.getElementById('bgp-nets-count-badge');
  6453. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  6454. const nets = state.bgpNets || [];
  6455. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  6456. if (navBadge) navBadge.innerText = nets.length;
  6457. if (nets.length === 0) {
  6458. tbody.innerHTML = '';
  6459. if (empty) empty.classList.remove('hidden');
  6460. return;
  6461. }
  6462. if (empty) empty.classList.add('hidden');
  6463. tbody.innerHTML = nets.map(n => `
  6464. <tr class="hover:bg-slate-800/40 transition">
  6465. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  6466. <td class="py-2.5 px-3">
  6467. ${n.disabled
  6468. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  6469. : '<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>'}
  6470. </td>
  6471. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  6472. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  6473. <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">
  6474. Delete
  6475. </button>
  6476. </td>
  6477. </tr>
  6478. `).join('');
  6479. }
  6480. function renderBgpRoutes() {
  6481. const tbody = document.getElementById('bgp-routes-table-body');
  6482. if (!tbody) return;
  6483. const empty = document.getElementById('bgp-routes-empty');
  6484. const countBadge = document.getElementById('bgp-routes-count-badge');
  6485. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  6486. const routes = state.bgpRoutes || [];
  6487. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  6488. if (navBadge) navBadge.innerText = routes.length;
  6489. if (routes.length === 0) {
  6490. tbody.innerHTML = '';
  6491. if (empty) empty.classList.remove('hidden');
  6492. return;
  6493. }
  6494. if (empty) empty.classList.add('hidden');
  6495. tbody.innerHTML = routes.map(r => `
  6496. <tr class="hover:bg-slate-800/40 transition">
  6497. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  6498. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  6499. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  6500. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  6501. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  6502. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  6503. </tr>
  6504. `).join('');
  6505. }
  6506. // =========================================================================
  6507. // ROUTEROS v7 OSPF TABLE RENDERING & SORTING
  6508. // =========================================================================
  6509. function sortOspfTable(tab, col) {
  6510. if (!state.ospfSort) state.ospfSort = {};
  6511. if (!state.ospfSort[tab]) state.ospfSort[tab] = { col: col, asc: true };
  6512. if (state.ospfSort[tab].col === col) {
  6513. state.ospfSort[tab].asc = !state.ospfSort[tab].asc;
  6514. } else {
  6515. state.ospfSort[tab].col = col;
  6516. state.ospfSort[tab].asc = true;
  6517. }
  6518. const asc = state.ospfSort[tab].asc;
  6519. let list = [];
  6520. if (tab === 'instances') list = state.ospfInstances || [];
  6521. else if (tab === 'areas') list = state.ospfAreas || [];
  6522. else if (tab === 'ranges') list = state.ospfAreaRanges || [];
  6523. else if (tab === 'templates') list = state.ospfTemplates || [];
  6524. else if (tab === 'live_ifaces') list = state.ospfLiveInterfaces || [];
  6525. else if (tab === 'snbrs') list = state.ospfStaticNbrs || [];
  6526. else if (tab === 'neighbors') list = state.ospfNeighbors || [];
  6527. else if (tab === 'lsa') list = state.ospfLSA || [];
  6528. list.sort((a, b) => {
  6529. let valA = a[col] ?? '';
  6530. let valB = b[col] ?? '';
  6531. if (typeof valA === 'number' && typeof valB === 'number') {
  6532. return asc ? valA - valB : valB - valA;
  6533. }
  6534. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  6535. });
  6536. if (tab === 'instances') renderOspfInstances();
  6537. else if (tab === 'areas') renderOspfAreas();
  6538. else if (tab === 'ranges') renderOspfAreaRanges();
  6539. else if (tab === 'templates') renderOspfTemplates();
  6540. else if (tab === 'live_ifaces') renderOspfLiveInterfaces();
  6541. else if (tab === 'snbrs') renderOspfStaticNbrs();
  6542. else if (tab === 'neighbors') renderOspfNeighbors();
  6543. else if (tab === 'lsa') renderOspfLSA();
  6544. }
  6545. function selectOspfRow(tab, id) {
  6546. if (!state.selectedOspfRow) state.selectedOspfRow = {};
  6547. state.selectedOspfRow[tab] = id;
  6548. if (tab === 'instances') {
  6549. renderOspfInstances();
  6550. const btnEn = document.getElementById('btn-ospf-inst-enable');
  6551. const btnDis = document.getElementById('btn-ospf-inst-disable');
  6552. const btnRem = document.getElementById('btn-ospf-inst-remove');
  6553. const btnCom = document.getElementById('btn-ospf-inst-comment');
  6554. if (btnEn) btnEn.disabled = false;
  6555. if (btnDis) btnDis.disabled = false;
  6556. if (btnRem) btnRem.disabled = false;
  6557. if (btnCom) btnCom.disabled = false;
  6558. } else if (tab === 'areas') {
  6559. renderOspfAreas();
  6560. const btnEn = document.getElementById('btn-ospf-area-enable');
  6561. const btnDis = document.getElementById('btn-ospf-area-disable');
  6562. const btnRem = document.getElementById('btn-ospf-area-remove');
  6563. const btnCom = document.getElementById('btn-ospf-area-comment');
  6564. if (btnEn) btnEn.disabled = false;
  6565. if (btnDis) btnDis.disabled = false;
  6566. if (btnRem) btnRem.disabled = false;
  6567. if (btnCom) btnCom.disabled = false;
  6568. } else if (tab === 'ranges') {
  6569. renderOspfAreaRanges();
  6570. const btnEn = document.getElementById('btn-ospf-range-enable');
  6571. const btnDis = document.getElementById('btn-ospf-range-disable');
  6572. const btnRem = document.getElementById('btn-ospf-range-remove');
  6573. const btnCom = document.getElementById('btn-ospf-range-comment');
  6574. if (btnEn) btnEn.disabled = false;
  6575. if (btnDis) btnDis.disabled = false;
  6576. if (btnRem) btnRem.disabled = false;
  6577. if (btnCom) btnCom.disabled = false;
  6578. } else if (tab === 'templates') {
  6579. renderOspfTemplates();
  6580. const btnEn = document.getElementById('btn-ospf-tmpl-enable');
  6581. const btnDis = document.getElementById('btn-ospf-tmpl-disable');
  6582. const btnRem = document.getElementById('btn-ospf-tmpl-remove');
  6583. const btnCom = document.getElementById('btn-ospf-tmpl-comment');
  6584. if (btnEn) btnEn.disabled = false;
  6585. if (btnDis) btnDis.disabled = false;
  6586. if (btnRem) btnRem.disabled = false;
  6587. if (btnCom) btnCom.disabled = false;
  6588. } else if (tab === 'snbrs') {
  6589. renderOspfStaticNbrs();
  6590. const btnEn = document.getElementById('btn-ospf-snbr-enable');
  6591. const btnDis = document.getElementById('btn-ospf-snbr-disable');
  6592. const btnRem = document.getElementById('btn-ospf-snbr-remove');
  6593. const btnCom = document.getElementById('btn-ospf-snbr-comment');
  6594. if (btnEn) btnEn.disabled = false;
  6595. if (btnDis) btnDis.disabled = false;
  6596. if (btnRem) btnRem.disabled = false;
  6597. if (btnCom) btnCom.disabled = false;
  6598. }
  6599. }
  6600. // TAB 1: INSTANCES
  6601. function renderOspfInstances() {
  6602. const tbody = document.getElementById('ospf-instances-table-body');
  6603. if (!tbody) return;
  6604. const countEl = document.getElementById('ospf-instances-footer-count');
  6605. const filter = (document.getElementById('filter-ospf-instances')?.value || '').toLowerCase();
  6606. let list = state.ospfInstances || [];
  6607. if (filter) {
  6608. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.router_id || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  6609. }
  6610. if (countEl) countEl.innerText = list.length;
  6611. const selId = state.selectedOspfRow?.instances;
  6612. tbody.innerHTML = list.map((inst, idx) => {
  6613. const isSel = inst.id === selId;
  6614. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  6615. const flagD = inst.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  6616. return `
  6617. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('instances', '${inst.id}')" ondblclick="openEditOspfInstanceModal('${inst.id}')">
  6618. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  6619. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  6620. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  6621. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  6622. <span class="text-sky-400">↳</span> <span>${escapeHtml(inst.name || 'Default')}</span>
  6623. </td>
  6624. <td class="py-1.5 px-3">${inst.version || 2}</td>
  6625. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(inst.vrf || 'main')}</td>
  6626. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(inst.router_id || '192.168.131.56')}</td>
  6627. </tr>
  6628. `;
  6629. }).join('');
  6630. }
  6631. // TAB 2: AREAS
  6632. function renderOspfAreas() {
  6633. const tbody = document.getElementById('ospf-areas-table-body');
  6634. if (!tbody) return;
  6635. const countEl = document.getElementById('ospf-areas-footer-count');
  6636. const filter = (document.getElementById('filter-ospf-areas')?.value || '').toLowerCase();
  6637. let list = state.ospfAreas || [];
  6638. if (filter) {
  6639. list = list.filter(a => (a.name || '').toLowerCase().includes(filter) || (a.area_id || '').toLowerCase().includes(filter) || (a.comment || '').toLowerCase().includes(filter));
  6640. }
  6641. if (countEl) countEl.innerText = list.length;
  6642. const selId = state.selectedOspfRow?.areas;
  6643. tbody.innerHTML = list.map((a, idx) => {
  6644. const isSel = a.id === selId;
  6645. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  6646. const flagD = a.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  6647. return `
  6648. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('areas', '${a.id}')" ondblclick="openEditOspfAreaModal('${a.id}')">
  6649. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  6650. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🌐'}</td>
  6651. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(a.comment || '')}</td>
  6652. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  6653. <span class="text-sky-400">↳</span> <span>${escapeHtml(a.name || 'Default')}</span>
  6654. </td>
  6655. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(a.instance || 'Default')}</td>
  6656. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(a.area_id || '0.0.0.0')}</td>
  6657. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(a.area_type || 'default')}</td>
  6658. </tr>
  6659. `;
  6660. }).join('');
  6661. }
  6662. // TAB 3: AREA RANGES
  6663. function renderOspfAreaRanges() {
  6664. const tbody = document.getElementById('ospf-ranges-table-body');
  6665. if (!tbody) return;
  6666. const countEl = document.getElementById('ospf-ranges-footer-count');
  6667. const filter = (document.getElementById('filter-ospf-area-ranges')?.value || '').toLowerCase();
  6668. let list = state.ospfAreaRanges || [];
  6669. if (filter) {
  6670. list = list.filter(r => (r.prefix || '').toLowerCase().includes(filter) || (r.area || '').toLowerCase().includes(filter) || (r.comment || '').toLowerCase().includes(filter));
  6671. }
  6672. if (countEl) countEl.innerText = list.length;
  6673. const selId = state.selectedOspfRow?.['area-ranges'];
  6674. tbody.innerHTML = list.map((r, idx) => {
  6675. const isSel = r.id === selId;
  6676. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  6677. const flagD = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  6678. return `
  6679. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('ranges', '${r.id}')" ondblclick="openEditOspfAreaRangeModal('${r.id}')">
  6680. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  6681. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🏷'}</td>
  6682. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(r.comment || '')}</td>
  6683. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(r.area || 'Default')}</td>
  6684. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(r.prefix || '')}</td>
  6685. <td class="py-1.5 px-3">${r.cost || 1}</td>
  6686. <td class="py-1.5 px-3">${r.advertise !== false ? 'yes' : 'no'}</td>
  6687. </tr>
  6688. `;
  6689. }).join('');
  6690. }
  6691. // TAB 4: INTERFACE TEMPLATES
  6692. function renderOspfTemplates() {
  6693. const tbody = document.getElementById('ospf-templates-table-body');
  6694. if (!tbody) return;
  6695. const countEl = document.getElementById('ospf-templates-footer-count');
  6696. const filter = (document.getElementById('filter-ospf-templates')?.value || '').toLowerCase();
  6697. let list = state.ospfTemplates || [];
  6698. if (filter) {
  6699. list = list.filter(t => (t.interfaces || t.interface || '').toLowerCase().includes(filter) || (t.networks || t.network || '').toLowerCase().includes(filter) || (t.comment || '').toLowerCase().includes(filter));
  6700. }
  6701. if (countEl) countEl.innerText = list.length;
  6702. const selId = state.selectedOspfRow?.templates;
  6703. tbody.innerHTML = list.map((t, idx) => {
  6704. const isSel = t.id === selId;
  6705. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  6706. const ifaces = t.interfaces || t.interface || 'all';
  6707. const nets = t.networks || t.network || '';
  6708. const flagD = t.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  6709. return `
  6710. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('templates', '${t.id}')" ondblclick="openEditOspfTemplateModal('${t.id}')">
  6711. <td class="py-1.5 px-3 w-8 text-center text-slate-500 font-bold">${idx}</td>
  6712. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  6713. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(t.comment || '')}</td>
  6714. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  6715. <span class="text-sky-400">↳</span> <span>${escapeHtml(ifaces)}</span>
  6716. </td>
  6717. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(t.area || 'Default')}</td>
  6718. <td class="py-1.5 px-3 font-mono text-sky-300">${escapeHtml(nets)}</td>
  6719. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(t.network_type || 'broadcast')}</td>
  6720. <td class="py-1.5 px-3">${t.cost || 1}</td>
  6721. <td class="py-1.5 px-3">${t.priority || 128}</td>
  6722. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(t.auth || t.auth_type || '')}</td>
  6723. </tr>
  6724. `;
  6725. }).join('');
  6726. }
  6727. // TAB 5: LIVE INTERFACES
  6728. function renderOspfLiveInterfaces() {
  6729. const tbody = document.getElementById('ospf-live-interfaces-table-body');
  6730. if (!tbody) return;
  6731. const countEl = document.getElementById('ospf-live-interfaces-footer-count');
  6732. const filter = (document.getElementById('filter-ospf-interfaces')?.value || '').toLowerCase();
  6733. let list = state.ospfLiveInterfaces || [];
  6734. if (filter) {
  6735. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.address || '').toLowerCase().includes(filter) || (i.state || '').toLowerCase().includes(filter));
  6736. }
  6737. if (countEl) countEl.innerText = list.length;
  6738. tbody.innerHTML = list.map(i => `
  6739. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  6740. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(i.flags || 'D')}</td>
  6741. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(i.interface || '')}</td>
  6742. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(i.address || '')}</td>
  6743. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(i.area || 'Default')}</td>
  6744. <td class="py-1.5 px-3 text-center text-slate-400">${i.instance_id || 0}</td>
  6745. <td class="py-1.5 px-3 font-mono text-amber-300 lowercase">${escapeHtml(i.state || 'waiting')}</td>
  6746. <td class="py-1.5 px-3">${i.cost || 1}</td>
  6747. <td class="py-1.5 px-3">${i.priority || 128}</td>
  6748. </tr>
  6749. `).join('');
  6750. }
  6751. // TAB 6: STATIC NEIGHBORS
  6752. function renderOspfStaticNbrs() {
  6753. const tbody = document.getElementById('ospf-snbrs-table-body');
  6754. if (!tbody) return;
  6755. const countEl = document.getElementById('ospf-snbrs-footer-count');
  6756. const filter = (document.getElementById('filter-ospf-static-nbrs')?.value || '').toLowerCase();
  6757. let list = state.ospfStaticNbrs || [];
  6758. if (filter) {
  6759. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.area || '').toLowerCase().includes(filter) || (n.comment || '').toLowerCase().includes(filter));
  6760. }
  6761. if (countEl) countEl.innerText = list.length;
  6762. const selId = state.selectedOspfRow?.['static-nbrs'];
  6763. tbody.innerHTML = list.map((n, idx) => {
  6764. const isSel = n.id === selId;
  6765. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  6766. const flagD = n.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  6767. return `
  6768. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('snbrs', '${n.id}')" ondblclick="openEditOspfStaticNbrModal('${n.id}')">
  6769. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  6770. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '📡'}</td>
  6771. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  6772. <td class="py-1.5 px-3 font-semibold font-mono text-sky-300">${escapeHtml(n.address || '')}</td>
  6773. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  6774. <td class="py-1.5 px-3">${n.poll_interval || 120}s</td>
  6775. <td class="py-1.5 px-3">${n.cost || 1}</td>
  6776. </tr>
  6777. `;
  6778. }).join('');
  6779. }
  6780. // TAB 7: LIVE NEIGHBORS
  6781. function renderOspfNeighbors() {
  6782. const tbody = document.getElementById('ospf-neighbors-table-body');
  6783. if (!tbody) return;
  6784. const countEl = document.getElementById('ospf-neighbors-footer-count');
  6785. const filter = (document.getElementById('filter-ospf-neighbors')?.value || '').toLowerCase();
  6786. let list = state.ospfNeighbors || [];
  6787. if (filter) {
  6788. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.state || '').toLowerCase().includes(filter) || (n.instance || '').toLowerCase().includes(filter));
  6789. }
  6790. if (countEl) countEl.innerText = list.length;
  6791. tbody.innerHTML = list.map(n => `
  6792. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  6793. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(n.flags || 'D')}</td>
  6794. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  6795. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  6796. <span class="text-sky-400">↳</span> <span>${escapeHtml(n.instance || 'Default')}</span>
  6797. </td>
  6798. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  6799. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(n.address || '')}</td>
  6800. <td class="py-1.5 px-3 font-mono font-bold text-emerald-400">${escapeHtml(n.state || 'Full')}</td>
  6801. <td class="py-1.5 px-3 text-slate-400">${n.state_changes ?? 6}</td>
  6802. </tr>
  6803. `).join('');
  6804. }
  6805. // TAB 8: LINK-STATE DATABASE (LSA)
  6806. function renderOspfLSA() {
  6807. const tbody = document.getElementById('ospf-lsa-table-body');
  6808. if (!tbody) return;
  6809. const countEl = document.getElementById('ospf-lsa-footer-count');
  6810. const filter = (document.getElementById('filter-ospf-lsa')?.value || '').toLowerCase();
  6811. let list = state.ospfLSA || [];
  6812. if (filter) {
  6813. list = list.filter(l => (l.type || '').toLowerCase().includes(filter) || (l.originator || '').toLowerCase().includes(filter) || (l.id || '').toLowerCase().includes(filter));
  6814. }
  6815. if (countEl) countEl.innerText = list.length;
  6816. tbody.innerHTML = list.map(l => `
  6817. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  6818. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(l.flags || 'D')}</td>
  6819. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  6820. <span class="text-sky-400">↳</span> <span>${escapeHtml(l.instance || 'Default')}</span>
  6821. </td>
  6822. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(l.area || 'Default')}</td>
  6823. <td class="py-1.5 px-3 font-mono text-amber-300">${escapeHtml(l.type || 'router')}</td>
  6824. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.originator || '')}</td>
  6825. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(l.id || '')}</td>
  6826. <td class="py-1.5 px-3 text-slate-500">${escapeHtml(l.link || '')}</td>
  6827. <td class="py-1.5 px-3 text-slate-500">${l.link_index ?? 0}</td>
  6828. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.sequence || '')}</td>
  6829. <td class="py-1.5 px-3 text-slate-400">${l.age ?? 0}</td>
  6830. </tr>
  6831. `).join('');
  6832. }
  6833. function renderOspfStatusPill() {
  6834. // Maintained for backward compatibility
  6835. const pill = document.getElementById('ospf-live-status-pill');
  6836. if (!pill) return;
  6837. 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';
  6838. pill.innerText = 'OSPF ACTIVE';
  6839. }
  6840. function renderOspfInterfaces() {
  6841. renderOspfTemplates();
  6842. }
  6843. function renderOspfRoutes() {
  6844. // Routes retained in background
  6845. }
  6846. // BGP Modals & Actions
  6847. function openBgpInstanceModal() {
  6848. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  6849. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  6850. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  6851. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  6852. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  6853. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  6854. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  6855. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  6856. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  6857. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  6858. }
  6859. function closeBgpInstanceModal() {
  6860. document.getElementById('bgp-instance-modal').classList.add('hidden');
  6861. }
  6862. async function submitBgpInstance(e) {
  6863. e.preventDefault();
  6864. const payload = {
  6865. enabled: document.getElementById('modal-bgp-enabled').checked,
  6866. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  6867. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  6868. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  6869. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  6870. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  6871. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  6872. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  6873. };
  6874. try {
  6875. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  6876. method: 'POST',
  6877. headers: { 'Content-Type': 'application/json' },
  6878. body: JSON.stringify(payload)
  6879. });
  6880. if (res.ok) {
  6881. closeBgpInstanceModal();
  6882. showToast('Success', 'BGP instance configuration updated', 'success');
  6883. loadDynamicRouting();
  6884. } else {
  6885. const err = await res.json();
  6886. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  6887. }
  6888. } catch (err) {
  6889. showToast('Error', err.message, 'error');
  6890. }
  6891. }
  6892. // ----------------- BGP Peer Connection Modal (RouterOS v7) -----------------
  6893. function switchBgpPeerModalTab(tab) {
  6894. const tabs = ['general', 'extra', 'attributes', 'filter'];
  6895. tabs.forEach(t => {
  6896. const pane = document.getElementById(`bgp-peer-tab-${t}`);
  6897. const btn = document.getElementById(`bgp-peer-tab-btn-${t}`);
  6898. if (t === tab) {
  6899. if (pane) pane.classList.remove('hidden');
  6900. if (btn) btn.className = 'px-4 py-2 text-xs font-bold border-b-2 border-cyan-500 text-white transition';
  6901. } else {
  6902. if (pane) pane.classList.add('hidden');
  6903. if (btn) btn.className = 'px-4 py-2 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition';
  6904. }
  6905. });
  6906. }
  6907. function addOutputNetworkRow(val = '') {
  6908. const container = document.getElementById('modal-bgp-output-networks-container');
  6909. if (!container) return;
  6910. const row = document.createElement('div');
  6911. row.className = 'flex items-center gap-2 output-net-row';
  6912. row.innerHTML = `
  6913. <input type="text" value="${escapeHtml(val)}" placeholder="e.g. 10.2.51.0/24 or BGP-AWMN" class="flex-1 bg-slate-900 border border-slate-700 rounded-lg px-3 py-1.5 text-white font-mono text-xs focus:outline-none focus:border-cyan-500">
  6914. <button type="button" onclick="this.closest('.output-net-row').remove()" class="w-7 h-7 flex items-center justify-center bg-slate-800 hover:bg-rose-950 text-slate-400 hover:text-rose-400 border border-slate-700 rounded-lg text-base font-bold transition" title="Remove network">-</button>
  6915. `;
  6916. container.appendChild(row);
  6917. }
  6918. function parseBgpTime(val) {
  6919. if (!val) return 0;
  6920. val = String(val).trim();
  6921. if (val.includes(':')) {
  6922. const parts = val.split(':').map(x => parseInt(x, 10) || 0);
  6923. if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2];
  6924. if (parts.length === 2) return parts[0] * 60 + parts[1];
  6925. }
  6926. return parseInt(val, 10) || 0;
  6927. }
  6928. function formatBgpTime(secs) {
  6929. if (!secs || secs <= 0) return '00:00:00';
  6930. const h = Math.floor(secs / 3600);
  6931. const m = Math.floor((secs % 3600) / 60);
  6932. const s = secs % 60;
  6933. return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
  6934. }
  6935. function populateBgpRoutingTables() {
  6936. const sel = document.getElementById('modal-bgp-peer-routing-table');
  6937. if (!sel) return;
  6938. const cur = sel.value || 'main';
  6939. sel.innerHTML = '<option value="main">main</option>';
  6940. (state.routingTables || []).forEach(t => {
  6941. if (t.name !== 'main') {
  6942. const opt = document.createElement('option');
  6943. opt.value = t.name;
  6944. opt.innerText = t.name;
  6945. sel.appendChild(opt);
  6946. }
  6947. });
  6948. sel.value = cur;
  6949. }
  6950. function openAddBgpPeerModal() {
  6951. document.getElementById('bgp-peer-form').reset();
  6952. document.getElementById('modal-bgp-peer-id').value = '';
  6953. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  6954. document.getElementById('modal-bgp-peer-enabled').checked = true;
  6955. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  6956. document.getElementById('modal-bgp-peer-afi-ipv6').checked = false;
  6957. document.getElementById('modal-bgp-peer-connect').checked = true;
  6958. document.getElementById('modal-bgp-peer-listen').checked = true;
  6959. document.getElementById('modal-bgp-peer-holdtime').value = '00:03:00';
  6960. document.getElementById('modal-bgp-peer-keepalive').value = '00:01:00';
  6961. document.getElementById('modal-bgp-peer-nexthop-choice').value = 'force-self';
  6962. document.getElementById('modal-bgp-peer-redist-conn').checked = false;
  6963. document.getElementById('modal-bgp-peer-redist-static').checked = true;
  6964. document.getElementById('modal-bgp-peer-redist-ospf').checked = false;
  6965. document.getElementById('modal-bgp-peer-redist-bgp').checked = false;
  6966. document.getElementById('modal-bgp-peer-default-orig').checked = false;
  6967. populateBgpRoutingTables();
  6968. const container = document.getElementById('modal-bgp-output-networks-container');
  6969. if (container) {
  6970. container.innerHTML = '';
  6971. addOutputNetworkRow('');
  6972. }
  6973. const removeBtn = document.getElementById('modal-btn-remove-peer');
  6974. if (removeBtn) removeBtn.classList.add('hidden');
  6975. switchBgpPeerModalTab('general');
  6976. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  6977. }
  6978. function openEditBgpPeerModal(id) {
  6979. const p = (state.bgpPeers || []).find(item => item.id === id);
  6980. if (!p) return;
  6981. populateBgpRoutingTables();
  6982. document.getElementById('modal-bgp-peer-id').value = p.id;
  6983. document.getElementById('bgp-peer-modal-title').innerText = p.name || p.id;
  6984. // General Tab
  6985. document.getElementById('modal-bgp-peer-enabled').checked = p.enabled !== false && !p.disabled;
  6986. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  6987. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  6988. document.getElementById('modal-bgp-peer-local-as').value = p.local_as || '';
  6989. document.getElementById('modal-bgp-peer-router-id').value = p.router_id || '';
  6990. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  6991. document.getElementById('modal-bgp-peer-afi-ipv6').checked = p.afi === 'ipv6';
  6992. document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  6993. document.getElementById('modal-bgp-peer-remote-port').value = p.remote_port || '';
  6994. document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  6995. document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  6996. document.getElementById('modal-bgp-peer-local-port').value = p.local_port || '';
  6997. document.getElementById('modal-bgp-peer-local-role').value = p.local_role || 'ebgp';
  6998. document.getElementById('modal-bgp-peer-password').value = p.password || '';
  6999. document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  7000. document.getElementById('modal-bgp-peer-connect').checked = p.connect !== false;
  7001. document.getElementById('modal-bgp-peer-listen').checked = p.listen !== false;
  7002. // Extra Tab
  7003. document.getElementById('modal-bgp-peer-holdtime').value = p.hold_time ? formatBgpTime(p.hold_time) : '00:03:00';
  7004. document.getElementById('modal-bgp-peer-keepalive').value = p.keepalive_time ? formatBgpTime(p.keepalive_time) : '00:01:00';
  7005. document.getElementById('modal-bgp-peer-routing-table').value = p.routing_table || 'main';
  7006. document.getElementById('modal-bgp-peer-redist-conn').checked = !!p.redist_connected;
  7007. document.getElementById('modal-bgp-peer-redist-static').checked = p.redist_static !== false;
  7008. document.getElementById('modal-bgp-peer-redist-ospf').checked = !!p.redist_ospf;
  7009. document.getElementById('modal-bgp-peer-redist-bgp').checked = !!p.redist_bgp;
  7010. document.getElementById('modal-bgp-peer-default-orig').checked = !!p.default_originate;
  7011. // Attributes Tab
  7012. document.getElementById('modal-bgp-peer-nexthop-choice').value = p.nexthop_choice || (p.nexthop_self ? 'force-self' : 'default');
  7013. document.getElementById('modal-bgp-peer-default-prepend').value = p.default_prepend || 0;
  7014. document.getElementById('modal-bgp-peer-allow-as-in').value = p.allow_as_in || 0;
  7015. document.getElementById('modal-bgp-peer-remove-priv-as').checked = !!p.remove_private_as;
  7016. document.getElementById('modal-bgp-peer-as-override').checked = !!p.as_override;
  7017. // Filter Tab
  7018. document.getElementById('modal-bgp-peer-in-filter').value = p.in_filter || '';
  7019. document.getElementById('modal-bgp-peer-out-filter').value = p.out_filter || '';
  7020. // Output Networks
  7021. const container = document.getElementById('modal-bgp-output-networks-container');
  7022. if (container) {
  7023. container.innerHTML = '';
  7024. if (p.output_networks && p.output_networks.length > 0) {
  7025. p.output_networks.forEach(net => addOutputNetworkRow(net));
  7026. } else {
  7027. addOutputNetworkRow('');
  7028. }
  7029. }
  7030. const removeBtn = document.getElementById('modal-btn-remove-peer');
  7031. if (removeBtn) removeBtn.classList.remove('hidden');
  7032. switchBgpPeerModalTab('general');
  7033. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  7034. }
  7035. function copyCurrentBgpPeer() {
  7036. document.getElementById('modal-bgp-peer-id').value = '';
  7037. const nameEl = document.getElementById('modal-bgp-peer-name');
  7038. if (nameEl) nameEl.value = (nameEl.value || 'peer') + '-copy';
  7039. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  7040. const removeBtn = document.getElementById('modal-btn-remove-peer');
  7041. if (removeBtn) removeBtn.classList.add('hidden');
  7042. showToast('Cloned', 'BGP connection copied to new draft', 'info');
  7043. }
  7044. function removeCurrentBgpPeer() {
  7045. const id = document.getElementById('modal-bgp-peer-id')?.value;
  7046. if (!id) return;
  7047. deleteBgpPeer(id);
  7048. closeBgpPeerModal();
  7049. }
  7050. function closeBgpPeerModal() {
  7051. document.getElementById('bgp-peer-modal').classList.add('hidden');
  7052. }
  7053. function getBgpPeerFormData() {
  7054. const netInputs = document.querySelectorAll('#modal-bgp-output-networks-container .output-net-row input');
  7055. const outputNetworks = [];
  7056. netInputs.forEach(inp => {
  7057. const v = inp.value.trim();
  7058. if (v) outputNetworks.push(v);
  7059. });
  7060. const enabled = document.getElementById('modal-bgp-peer-enabled').checked;
  7061. return {
  7062. id: document.getElementById('modal-bgp-peer-id').value,
  7063. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  7064. enabled: enabled,
  7065. disabled: !enabled,
  7066. comment: document.getElementById('modal-bgp-peer-comment').value.trim(),
  7067. local_as: parseInt(document.getElementById('modal-bgp-peer-local-as')?.value, 10) || 0,
  7068. router_id: document.getElementById('modal-bgp-peer-router-id').value.trim(),
  7069. afi: document.getElementById('modal-bgp-peer-afi-ipv6').checked ? 'ipv6' : 'ip',
  7070. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  7071. remote_port: parseInt(document.getElementById('modal-bgp-peer-remote-port').value, 10) || 0,
  7072. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10) || 0,
  7073. local_address: document.getElementById('modal-bgp-peer-local-addr').value.trim(),
  7074. local_port: parseInt(document.getElementById('modal-bgp-peer-local-port').value, 10) || 0,
  7075. local_role: document.getElementById('modal-bgp-peer-local-role').value,
  7076. password: document.getElementById('modal-bgp-peer-password').value,
  7077. multihop: document.getElementById('modal-bgp-peer-multihop').checked,
  7078. connect: document.getElementById('modal-bgp-peer-connect').checked,
  7079. listen: document.getElementById('modal-bgp-peer-listen').checked,
  7080. hold_time: parseBgpTime(document.getElementById('modal-bgp-peer-holdtime').value),
  7081. keepalive_time: parseBgpTime(document.getElementById('modal-bgp-peer-keepalive').value),
  7082. routing_table: document.getElementById('modal-bgp-peer-routing-table').value,
  7083. redist_connected: document.getElementById('modal-bgp-peer-redist-conn').checked,
  7084. redist_static: document.getElementById('modal-bgp-peer-redist-static').checked,
  7085. redist_ospf: document.getElementById('modal-bgp-peer-redist-ospf').checked,
  7086. redist_bgp: document.getElementById('modal-bgp-peer-redist-bgp').checked,
  7087. default_originate: document.getElementById('modal-bgp-peer-default-orig').checked,
  7088. nexthop_choice: document.getElementById('modal-bgp-peer-nexthop-choice').value,
  7089. nexthop_self: document.getElementById('modal-bgp-peer-nexthop-choice').value === 'force-self',
  7090. default_prepend: parseInt(document.getElementById('modal-bgp-peer-default-prepend').value, 10) || 0,
  7091. allow_as_in: parseInt(document.getElementById('modal-bgp-peer-allow-as-in').value, 10) || 0,
  7092. remove_private_as: document.getElementById('modal-bgp-peer-remove-priv-as').checked,
  7093. as_override: document.getElementById('modal-bgp-peer-as-override').checked,
  7094. in_filter: (document.getElementById('modal-bgp-peer-in-filter')?.value || '').trim(),
  7095. out_filter: (document.getElementById('modal-bgp-peer-out-filter')?.value || '').trim(),
  7096. output_networks: outputNetworks
  7097. };
  7098. }
  7099. async function submitBgpPeer(e) {
  7100. if (e) e.preventDefault();
  7101. const payload = getBgpPeerFormData();
  7102. try {
  7103. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  7104. method: 'POST',
  7105. headers: { 'Content-Type': 'application/json' },
  7106. body: JSON.stringify(payload)
  7107. });
  7108. if (res.ok) {
  7109. closeBgpPeerModal();
  7110. showToast('Success', 'BGP Connection saved', 'success');
  7111. loadDynamicRouting();
  7112. } else {
  7113. const err = await res.json();
  7114. showToast('Error', err.error || 'Failed to save peer', 'error');
  7115. }
  7116. } catch (err) {
  7117. showToast('Error', err.message, 'error');
  7118. }
  7119. }
  7120. async function applyBgpPeerModal(e) {
  7121. if (e) e.preventDefault();
  7122. const payload = getBgpPeerFormData();
  7123. try {
  7124. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  7125. method: 'POST',
  7126. headers: { 'Content-Type': 'application/json' },
  7127. body: JSON.stringify(payload)
  7128. });
  7129. if (res.ok) {
  7130. const data = await res.json();
  7131. if (data.peer && data.peer.id) {
  7132. document.getElementById('modal-bgp-peer-id').value = data.peer.id;
  7133. document.getElementById('bgp-peer-modal-title').innerText = data.peer.name || data.peer.id;
  7134. document.getElementById('modal-btn-remove-peer')?.classList.remove('hidden');
  7135. }
  7136. showToast('Applied', 'BGP Connection applied', 'success');
  7137. loadDynamicRouting();
  7138. } else {
  7139. const err = await res.json();
  7140. showToast('Error', err.error || 'Failed to apply peer', 'error');
  7141. }
  7142. } catch (err) {
  7143. showToast('Error', err.message, 'error');
  7144. }
  7145. }
  7146. async function deleteBgpPeer(id) {
  7147. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  7148. try {
  7149. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7150. if (res.ok) {
  7151. showToast('Deleted', 'BGP peer removed', 'success');
  7152. loadDynamicRouting();
  7153. }
  7154. } catch (err) {
  7155. showToast('Error', err.message, 'error');
  7156. }
  7157. }
  7158. async function toggleBgpPeerState(id, disabled) {
  7159. try {
  7160. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  7161. method: 'POST',
  7162. headers: { 'Content-Type': 'application/json' },
  7163. body: JSON.stringify({ disabled })
  7164. });
  7165. if (res.ok) {
  7166. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  7167. loadDynamicRouting();
  7168. }
  7169. } catch (err) {
  7170. showToast('Error', err.message, 'error');
  7171. }
  7172. }
  7173. function openAddBgpNetworkModal() {
  7174. document.getElementById('bgp-network-form').reset();
  7175. document.getElementById('modal-bgp-net-id').value = '';
  7176. document.getElementById('bgp-network-modal').classList.remove('hidden');
  7177. }
  7178. function closeBgpNetworkModal() {
  7179. document.getElementById('bgp-network-modal').classList.add('hidden');
  7180. }
  7181. async function submitBgpNetwork(e) {
  7182. e.preventDefault();
  7183. const payload = {
  7184. id: document.getElementById('modal-bgp-net-id').value,
  7185. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  7186. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  7187. disabled: document.getElementById('modal-bgp-net-disabled').checked
  7188. };
  7189. try {
  7190. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  7191. method: 'POST',
  7192. headers: { 'Content-Type': 'application/json' },
  7193. body: JSON.stringify(payload)
  7194. });
  7195. if (res.ok) {
  7196. closeBgpNetworkModal();
  7197. showToast('Success', 'BGP network advertisement saved', 'success');
  7198. loadDynamicRouting();
  7199. } else {
  7200. const err = await res.json();
  7201. showToast('Error', err.error || 'Failed to save network', 'error');
  7202. }
  7203. } catch (err) {
  7204. showToast('Error', err.message, 'error');
  7205. }
  7206. }
  7207. async function deleteBgpNetwork(id) {
  7208. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  7209. try {
  7210. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7211. if (res.ok) {
  7212. showToast('Deleted', 'Network advertisement removed', 'success');
  7213. loadDynamicRouting();
  7214. }
  7215. } catch (err) {
  7216. showToast('Error', err.message, 'error');
  7217. }
  7218. }
  7219. // =========================================================================
  7220. // ROUTEROS v7 OSPF MODALS & ACTIONS
  7221. // =========================================================================
  7222. // --- 1. OSPF INSTANCE ---
  7223. function openOspfInstanceModal(id = null) {
  7224. const isEdit = !!id;
  7225. const inst = (state.ospfInstances || []).find(i => i.id === id) || {
  7226. id: '',
  7227. name: 'Default',
  7228. version: 2,
  7229. vrf: 'main',
  7230. router_id: '192.168.131.56',
  7231. routing_table: 'main',
  7232. enabled: true,
  7233. redistribute_connected: false,
  7234. redistribute_static: true,
  7235. redistribute_bgp: false,
  7236. comment: ''
  7237. };
  7238. document.getElementById('ospf-instance-modal-title').innerText = isEdit ? inst.name : 'New...';
  7239. document.getElementById('modal-ospf-inst-id').value = isEdit ? inst.id : '';
  7240. document.getElementById('modal-ospf-inst-enabled').checked = !inst.disabled;
  7241. document.getElementById('modal-ospf-inst-comment').value = inst.comment || '';
  7242. document.getElementById('modal-ospf-inst-name').value = inst.name || 'Default';
  7243. document.getElementById('modal-ospf-inst-version').value = inst.version || 2;
  7244. document.getElementById('modal-ospf-inst-vrf').value = inst.vrf || 'main';
  7245. document.getElementById('modal-ospf-inst-router-id').value = inst.router_id || '';
  7246. document.getElementById('modal-ospf-inst-routing-table').value = inst.routing_table || 'main';
  7247. document.getElementById('modal-ospf-inst-redist-conn').checked = !!inst.redistribute_connected;
  7248. document.getElementById('modal-ospf-inst-redist-static').checked = inst.redistribute_static !== false;
  7249. document.getElementById('modal-ospf-inst-redist-bgp').checked = !!inst.redistribute_bgp;
  7250. const btnRem = document.getElementById('btn-ospf-inst-modal-remove');
  7251. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  7252. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  7253. }
  7254. function openEditOspfInstanceModal(id) {
  7255. openOspfInstanceModal(id);
  7256. }
  7257. function closeOspfInstanceModal() {
  7258. document.getElementById('ospf-instance-modal').classList.add('hidden');
  7259. }
  7260. async function submitOspfInstance(e) {
  7261. if (e) e.preventDefault();
  7262. const payload = {
  7263. id: document.getElementById('modal-ospf-inst-id').value,
  7264. name: document.getElementById('modal-ospf-inst-name').value.trim() || 'Default',
  7265. version: parseInt(document.getElementById('modal-ospf-inst-version').value, 10) || 2,
  7266. vrf: document.getElementById('modal-ospf-inst-vrf').value.trim() || 'main',
  7267. router_id: document.getElementById('modal-ospf-inst-router-id').value.trim(),
  7268. routing_table: document.getElementById('modal-ospf-inst-routing-table').value.trim() || 'main',
  7269. enabled: document.getElementById('modal-ospf-inst-enabled').checked,
  7270. disabled: !document.getElementById('modal-ospf-inst-enabled').checked,
  7271. comment: document.getElementById('modal-ospf-inst-comment').value.trim(),
  7272. redistribute_connected: document.getElementById('modal-ospf-inst-redist-conn').checked,
  7273. redistribute_static: document.getElementById('modal-ospf-inst-redist-static').checked,
  7274. redistribute_bgp: document.getElementById('modal-ospf-inst-redist-bgp').checked
  7275. };
  7276. try {
  7277. const res = await fetch(`${API_BASE}/routing/ospf/instances`, {
  7278. method: 'POST',
  7279. headers: { 'Content-Type': 'application/json' },
  7280. body: JSON.stringify(payload)
  7281. });
  7282. if (res.ok) {
  7283. closeOspfInstanceModal();
  7284. showToast('Saved', 'OSPF instance updated', 'success');
  7285. loadDynamicRouting();
  7286. } else {
  7287. const err = await res.json();
  7288. showToast('Error', err.error || 'Failed to save OSPF instance', 'error');
  7289. }
  7290. } catch (err) {
  7291. showToast('Error', err.message, 'error');
  7292. }
  7293. }
  7294. function applyOspfInstanceForm() {
  7295. submitOspfInstance(null);
  7296. }
  7297. function copyOspfInstance() {
  7298. document.getElementById('modal-ospf-inst-id').value = '';
  7299. document.getElementById('modal-ospf-inst-name').value += '-copy';
  7300. document.getElementById('ospf-instance-modal-title').innerText = 'New...';
  7301. showToast('Copied', 'Duplicated as new OSPF instance', 'info');
  7302. }
  7303. async function deleteCurrentOspfInstance() {
  7304. const id = document.getElementById('modal-ospf-inst-id').value;
  7305. if (!id) return;
  7306. if (!confirm('Are you sure you want to remove this OSPF instance?')) return;
  7307. try {
  7308. const res = await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7309. if (res.ok) {
  7310. closeOspfInstanceModal();
  7311. showToast('Removed', 'OSPF instance deleted', 'success');
  7312. loadDynamicRouting();
  7313. }
  7314. } catch (err) {
  7315. showToast('Error', err.message, 'error');
  7316. }
  7317. }
  7318. async function enableSelectedOspfInstance() {
  7319. const id = state.selectedOspfRow?.instances;
  7320. if (!id) return;
  7321. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  7322. method: 'POST',
  7323. headers: { 'Content-Type': 'application/json' },
  7324. body: JSON.stringify({ disabled: false })
  7325. });
  7326. loadDynamicRouting();
  7327. }
  7328. async function disableSelectedOspfInstance() {
  7329. const id = state.selectedOspfRow?.instances;
  7330. if (!id) return;
  7331. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  7332. method: 'POST',
  7333. headers: { 'Content-Type': 'application/json' },
  7334. body: JSON.stringify({ disabled: true })
  7335. });
  7336. loadDynamicRouting();
  7337. }
  7338. async function removeSelectedOspfInstance() {
  7339. const id = state.selectedOspfRow?.instances;
  7340. if (!id) return;
  7341. if (!confirm('Delete selected OSPF instance?')) return;
  7342. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7343. loadDynamicRouting();
  7344. }
  7345. async function promptCommentOspfInstance() {
  7346. const id = state.selectedOspfRow?.instances;
  7347. if (!id) return;
  7348. const inst = (state.ospfInstances || []).find(i => i.id === id);
  7349. if (!inst) return;
  7350. const comment = prompt('Enter comment for OSPF instance:', inst.comment || '');
  7351. if (comment === null) return;
  7352. inst.comment = comment;
  7353. await fetch(`${API_BASE}/routing/ospf/instances`, {
  7354. method: 'POST',
  7355. headers: { 'Content-Type': 'application/json' },
  7356. body: JSON.stringify(inst)
  7357. });
  7358. loadDynamicRouting();
  7359. }
  7360. // --- 2. OSPF AREA ---
  7361. function populateOspfAreaDropdowns() {
  7362. const instSelect = document.getElementById('modal-ospf-area-instance');
  7363. if (instSelect) {
  7364. const cur = instSelect.value;
  7365. instSelect.innerHTML = (state.ospfInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  7366. if (instSelect.innerHTML === '') instSelect.innerHTML = '<option value="Default">Default</option>';
  7367. if (cur) instSelect.value = cur;
  7368. }
  7369. }
  7370. function openOspfAreaModal(id = null) {
  7371. const isEdit = !!id;
  7372. populateOspfAreaDropdowns();
  7373. const area = (state.ospfAreas || []).find(a => a.id === id) || {
  7374. id: '',
  7375. name: 'Default',
  7376. instance: 'Default',
  7377. area_id: '0.0.0.0',
  7378. area_type: 'default',
  7379. default_cost: 1,
  7380. no_summaries: false,
  7381. disabled: false,
  7382. comment: ''
  7383. };
  7384. document.getElementById('ospf-area-modal-title').innerText = isEdit ? area.name : 'New...';
  7385. document.getElementById('modal-ospf-area-id').value = isEdit ? area.id : '';
  7386. document.getElementById('modal-ospf-area-enabled').checked = !area.disabled;
  7387. document.getElementById('modal-ospf-area-comment').value = area.comment || '';
  7388. document.getElementById('modal-ospf-area-name').value = area.name || 'Default';
  7389. document.getElementById('modal-ospf-area-instance').value = area.instance || 'Default';
  7390. document.getElementById('modal-ospf-area-areaid').value = area.area_id || '0.0.0.0';
  7391. document.getElementById('modal-ospf-area-type').value = area.area_type || 'default';
  7392. document.getElementById('modal-ospf-area-default-cost').value = area.default_cost || 1;
  7393. document.getElementById('modal-ospf-area-no-summaries').checked = !!area.no_summaries;
  7394. const btnRem = document.getElementById('btn-ospf-area-modal-remove');
  7395. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  7396. document.getElementById('ospf-area-modal').classList.remove('hidden');
  7397. }
  7398. function openEditOspfAreaModal(id) {
  7399. openOspfAreaModal(id);
  7400. }
  7401. function closeOspfAreaModal() {
  7402. document.getElementById('ospf-area-modal').classList.add('hidden');
  7403. }
  7404. async function submitOspfArea(e) {
  7405. if (e) e.preventDefault();
  7406. const payload = {
  7407. id: document.getElementById('modal-ospf-area-id').value,
  7408. name: document.getElementById('modal-ospf-area-name').value.trim() || 'Default',
  7409. instance: document.getElementById('modal-ospf-area-instance').value.trim() || 'Default',
  7410. area_id: document.getElementById('modal-ospf-area-areaid').value.trim() || '0.0.0.0',
  7411. area_type: document.getElementById('modal-ospf-area-type').value,
  7412. default_cost: parseInt(document.getElementById('modal-ospf-area-default-cost').value, 10) || 1,
  7413. no_summaries: document.getElementById('modal-ospf-area-no-summaries').checked,
  7414. disabled: !document.getElementById('modal-ospf-area-enabled').checked,
  7415. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  7416. };
  7417. try {
  7418. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  7419. method: 'POST',
  7420. headers: { 'Content-Type': 'application/json' },
  7421. body: JSON.stringify(payload)
  7422. });
  7423. if (res.ok) {
  7424. closeOspfAreaModal();
  7425. showToast('Saved', 'OSPF area saved', 'success');
  7426. loadDynamicRouting();
  7427. } else {
  7428. const err = await res.json();
  7429. showToast('Error', err.error || 'Failed to save area', 'error');
  7430. }
  7431. } catch (err) {
  7432. showToast('Error', err.message, 'error');
  7433. }
  7434. }
  7435. function applyOspfAreaForm() {
  7436. submitOspfArea(null);
  7437. }
  7438. function copyOspfArea() {
  7439. document.getElementById('modal-ospf-area-id').value = '';
  7440. document.getElementById('modal-ospf-area-name').value += '-copy';
  7441. document.getElementById('ospf-area-modal-title').innerText = 'New...';
  7442. showToast('Copied', 'Duplicated as new OSPF area', 'info');
  7443. }
  7444. async function deleteCurrentOspfArea() {
  7445. const id = document.getElementById('modal-ospf-area-id').value;
  7446. if (!id) return;
  7447. if (!confirm('Are you sure you want to remove this OSPF area?')) return;
  7448. try {
  7449. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7450. if (res.ok) {
  7451. closeOspfAreaModal();
  7452. showToast('Removed', 'OSPF area deleted', 'success');
  7453. loadDynamicRouting();
  7454. }
  7455. } catch (err) {
  7456. showToast('Error', err.message, 'error');
  7457. }
  7458. }
  7459. async function enableSelectedOspfArea() {
  7460. const id = state.selectedOspfRow?.areas;
  7461. if (!id) return;
  7462. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  7463. method: 'POST',
  7464. headers: { 'Content-Type': 'application/json' },
  7465. body: JSON.stringify({ disabled: false })
  7466. });
  7467. loadDynamicRouting();
  7468. }
  7469. async function disableSelectedOspfArea() {
  7470. const id = state.selectedOspfRow?.areas;
  7471. if (!id) return;
  7472. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  7473. method: 'POST',
  7474. headers: { 'Content-Type': 'application/json' },
  7475. body: JSON.stringify({ disabled: true })
  7476. });
  7477. loadDynamicRouting();
  7478. }
  7479. async function removeSelectedOspfArea() {
  7480. const id = state.selectedOspfRow?.areas;
  7481. if (!id) return;
  7482. if (!confirm('Delete selected OSPF area?')) return;
  7483. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7484. loadDynamicRouting();
  7485. }
  7486. async function promptCommentOspfArea() {
  7487. const id = state.selectedOspfRow?.areas;
  7488. if (!id) return;
  7489. const area = (state.ospfAreas || []).find(a => a.id === id);
  7490. if (!area) return;
  7491. const comment = prompt('Enter comment for OSPF area:', area.comment || '');
  7492. if (comment === null) return;
  7493. area.comment = comment;
  7494. await fetch(`${API_BASE}/routing/ospf/areas`, {
  7495. method: 'POST',
  7496. headers: { 'Content-Type': 'application/json' },
  7497. body: JSON.stringify(area)
  7498. });
  7499. loadDynamicRouting();
  7500. }
  7501. // --- 3. OSPF AREA RANGE ---
  7502. function populateAreaRangeDropdowns() {
  7503. const select = document.getElementById('modal-ospf-range-area');
  7504. if (select) {
  7505. const cur = select.value;
  7506. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  7507. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  7508. if (cur) select.value = cur;
  7509. }
  7510. }
  7511. function openOspfAreaRangeModal(id = null) {
  7512. const isEdit = !!id;
  7513. populateAreaRangeDropdowns();
  7514. const r = (state.ospfAreaRanges || []).find(it => it.id === id) || {
  7515. id: '',
  7516. area: 'Default',
  7517. prefix: '',
  7518. cost: 1,
  7519. advertise: true,
  7520. disabled: false,
  7521. comment: ''
  7522. };
  7523. document.getElementById('ospf-area-range-modal-title').innerText = isEdit ? r.prefix : 'New...';
  7524. document.getElementById('modal-ospf-range-id').value = isEdit ? r.id : '';
  7525. document.getElementById('modal-ospf-range-enabled').checked = !r.disabled;
  7526. document.getElementById('modal-ospf-range-comment').value = r.comment || '';
  7527. document.getElementById('modal-ospf-range-area').value = r.area || 'Default';
  7528. document.getElementById('modal-ospf-range-prefix').value = r.prefix || '';
  7529. document.getElementById('modal-ospf-range-cost').value = r.cost || 1;
  7530. document.getElementById('modal-ospf-range-advertise').checked = r.advertise !== false;
  7531. const btnRem = document.getElementById('btn-ospf-range-modal-remove');
  7532. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  7533. document.getElementById('ospf-area-range-modal').classList.remove('hidden');
  7534. }
  7535. function openEditOspfAreaRangeModal(id) {
  7536. openOspfAreaRangeModal(id);
  7537. }
  7538. function closeOspfAreaRangeModal() {
  7539. document.getElementById('ospf-area-range-modal').classList.add('hidden');
  7540. }
  7541. async function submitOspfAreaRange(e) {
  7542. if (e) e.preventDefault();
  7543. const payload = {
  7544. id: document.getElementById('modal-ospf-range-id').value,
  7545. area: document.getElementById('modal-ospf-range-area').value,
  7546. prefix: document.getElementById('modal-ospf-range-prefix').value.trim(),
  7547. cost: parseInt(document.getElementById('modal-ospf-range-cost').value, 10) || 1,
  7548. advertise: document.getElementById('modal-ospf-range-advertise').checked,
  7549. disabled: !document.getElementById('modal-ospf-range-enabled').checked,
  7550. comment: document.getElementById('modal-ospf-range-comment').value.trim()
  7551. };
  7552. try {
  7553. const res = await fetch(`${API_BASE}/routing/ospf/area-ranges`, {
  7554. method: 'POST',
  7555. headers: { 'Content-Type': 'application/json' },
  7556. body: JSON.stringify(payload)
  7557. });
  7558. if (res.ok) {
  7559. closeOspfAreaRangeModal();
  7560. showToast('Saved', 'Area range saved', 'success');
  7561. loadDynamicRouting();
  7562. } else {
  7563. const err = await res.json();
  7564. showToast('Error', err.error || 'Failed to save area range', 'error');
  7565. }
  7566. } catch (err) {
  7567. showToast('Error', err.message, 'error');
  7568. }
  7569. }
  7570. function applyOspfAreaRangeForm() {
  7571. submitOspfAreaRange(null);
  7572. }
  7573. async function deleteCurrentOspfAreaRange() {
  7574. const id = document.getElementById('modal-ospf-range-id').value;
  7575. if (!id) return;
  7576. if (!confirm('Delete this area range?')) return;
  7577. try {
  7578. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7579. closeOspfAreaRangeModal();
  7580. showToast('Removed', 'Area range removed', 'success');
  7581. loadDynamicRouting();
  7582. } catch (err) {
  7583. showToast('Error', err.message, 'error');
  7584. }
  7585. }
  7586. async function enableSelectedOspfAreaRange() {
  7587. const id = state.selectedOspfRow?.['area-ranges'];
  7588. if (!id) return;
  7589. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  7590. if (!r) return;
  7591. r.disabled = false;
  7592. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  7593. loadDynamicRouting();
  7594. }
  7595. async function disableSelectedOspfAreaRange() {
  7596. const id = state.selectedOspfRow?.['area-ranges'];
  7597. if (!id) return;
  7598. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  7599. if (!r) return;
  7600. r.disabled = true;
  7601. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  7602. loadDynamicRouting();
  7603. }
  7604. async function removeSelectedOspfAreaRange() {
  7605. const id = state.selectedOspfRow?.['area-ranges'];
  7606. if (!id) return;
  7607. if (!confirm('Delete selected area range?')) return;
  7608. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7609. loadDynamicRouting();
  7610. }
  7611. async function promptCommentOspfAreaRange() {
  7612. const id = state.selectedOspfRow?.['area-ranges'];
  7613. if (!id) return;
  7614. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  7615. if (!r) return;
  7616. const comment = prompt('Enter comment for area range:', r.comment || '');
  7617. if (comment === null) return;
  7618. r.comment = comment;
  7619. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  7620. loadDynamicRouting();
  7621. }
  7622. // --- 4. OSPF INTERFACE TEMPLATE ---
  7623. function switchOspfTemplateTab(tab) {
  7624. const tabGen = document.getElementById('ospf-tmpl-tab-general');
  7625. const tabAuth = document.getElementById('ospf-tmpl-tab-auth');
  7626. const btnGen = document.getElementById('ospf-tmpl-tab-btn-general');
  7627. const btnAuth = document.getElementById('ospf-tmpl-tab-btn-auth');
  7628. if (tab === 'general') {
  7629. if (tabGen) tabGen.classList.remove('hidden');
  7630. if (tabAuth) tabAuth.classList.add('hidden');
  7631. if (btnGen) btnGen.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  7632. if (btnAuth) btnAuth.className = 'px-4 py-2 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition';
  7633. } else {
  7634. if (tabGen) tabGen.classList.add('hidden');
  7635. if (tabAuth) tabAuth.classList.remove('hidden');
  7636. if (btnGen) btnGen.className = 'px-4 py-2 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition';
  7637. if (btnAuth) btnAuth.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  7638. }
  7639. }
  7640. function populateTemplateAreaDropdowns() {
  7641. const select = document.getElementById('modal-ospf-tmpl-area');
  7642. if (select) {
  7643. const cur = select.value;
  7644. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  7645. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  7646. if (cur) select.value = cur;
  7647. }
  7648. }
  7649. function openOspfTemplateModal(id = null) {
  7650. const isEdit = !!id;
  7651. populateTemplateAreaDropdowns();
  7652. switchOspfTemplateTab('general');
  7653. const tmpl = (state.ospfTemplates || []).find(t => t.id === id) || {
  7654. id: '',
  7655. interfaces: '',
  7656. area: 'Default',
  7657. networks: '',
  7658. network_type: 'broadcast',
  7659. cost: 1,
  7660. priority: 128,
  7661. passive: false,
  7662. hello_interval: 10,
  7663. dead_interval: 40,
  7664. auth: 'none',
  7665. auth_key: '',
  7666. disabled: false,
  7667. comment: ''
  7668. };
  7669. document.getElementById('ospf-template-modal-title').innerText = isEdit ? (tmpl.interfaces || tmpl.networks || 'Template') : 'New...';
  7670. document.getElementById('modal-ospf-tmpl-id').value = isEdit ? tmpl.id : '';
  7671. document.getElementById('modal-ospf-tmpl-enabled').checked = !tmpl.disabled;
  7672. document.getElementById('modal-ospf-tmpl-comment').value = tmpl.comment || '';
  7673. document.getElementById('modal-ospf-tmpl-interfaces').value = tmpl.interfaces || tmpl.interface || '';
  7674. document.getElementById('modal-ospf-tmpl-area').value = tmpl.area || 'Default';
  7675. document.getElementById('modal-ospf-tmpl-networks').value = tmpl.networks || tmpl.network || '';
  7676. document.getElementById('modal-ospf-tmpl-net-type').value = tmpl.network_type || 'broadcast';
  7677. document.getElementById('modal-ospf-tmpl-cost').value = tmpl.cost || 1;
  7678. document.getElementById('modal-ospf-tmpl-priority').value = tmpl.priority || 128;
  7679. document.getElementById('modal-ospf-tmpl-passive').checked = !!tmpl.passive;
  7680. document.getElementById('modal-ospf-tmpl-hello').value = tmpl.hello_interval || 10;
  7681. document.getElementById('modal-ospf-tmpl-dead').value = tmpl.dead_interval || 40;
  7682. document.getElementById('modal-ospf-tmpl-auth').value = tmpl.auth || tmpl.auth_type || 'none';
  7683. document.getElementById('modal-ospf-tmpl-auth-key').value = tmpl.auth_key || '';
  7684. const btnRem = document.getElementById('btn-ospf-tmpl-modal-remove');
  7685. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  7686. document.getElementById('ospf-template-modal').classList.remove('hidden');
  7687. }
  7688. function openEditOspfTemplateModal(id) {
  7689. openOspfTemplateModal(id);
  7690. }
  7691. function closeOspfTemplateModal() {
  7692. document.getElementById('ospf-template-modal').classList.add('hidden');
  7693. }
  7694. async function submitOspfTemplate(e) {
  7695. if (e) e.preventDefault();
  7696. const payload = {
  7697. id: document.getElementById('modal-ospf-tmpl-id').value,
  7698. interfaces: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  7699. interface: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  7700. area: document.getElementById('modal-ospf-tmpl-area').value,
  7701. networks: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  7702. network: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  7703. network_type: document.getElementById('modal-ospf-tmpl-net-type').value,
  7704. cost: parseInt(document.getElementById('modal-ospf-tmpl-cost').value, 10) || 1,
  7705. priority: parseInt(document.getElementById('modal-ospf-tmpl-priority').value, 10) || 128,
  7706. passive: document.getElementById('modal-ospf-tmpl-passive').checked,
  7707. hello_interval: parseInt(document.getElementById('modal-ospf-tmpl-hello').value, 10) || 10,
  7708. dead_interval: parseInt(document.getElementById('modal-ospf-tmpl-dead').value, 10) || 40,
  7709. auth: document.getElementById('modal-ospf-tmpl-auth').value,
  7710. auth_type: document.getElementById('modal-ospf-tmpl-auth').value,
  7711. auth_key: document.getElementById('modal-ospf-tmpl-auth-key').value,
  7712. disabled: !document.getElementById('modal-ospf-tmpl-enabled').checked,
  7713. comment: document.getElementById('modal-ospf-tmpl-comment').value.trim()
  7714. };
  7715. try {
  7716. const res = await fetch(`${API_BASE}/routing/ospf/templates`, {
  7717. method: 'POST',
  7718. headers: { 'Content-Type': 'application/json' },
  7719. body: JSON.stringify(payload)
  7720. });
  7721. if (res.ok) {
  7722. closeOspfTemplateModal();
  7723. showToast('Saved', 'Interface template saved', 'success');
  7724. loadDynamicRouting();
  7725. } else {
  7726. const err = await res.json();
  7727. showToast('Error', err.error || 'Failed to save interface template', 'error');
  7728. }
  7729. } catch (err) {
  7730. showToast('Error', err.message, 'error');
  7731. }
  7732. }
  7733. function applyOspfTemplateForm() {
  7734. submitOspfTemplate(null);
  7735. }
  7736. function copyOspfTemplate() {
  7737. document.getElementById('modal-ospf-tmpl-id').value = '';
  7738. document.getElementById('ospf-template-modal-title').innerText = 'New...';
  7739. showToast('Copied', 'Duplicated as new template', 'info');
  7740. }
  7741. async function deleteCurrentOspfTemplate() {
  7742. const id = document.getElementById('modal-ospf-tmpl-id').value;
  7743. if (!id) return;
  7744. if (!confirm('Delete this interface template?')) return;
  7745. try {
  7746. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7747. closeOspfTemplateModal();
  7748. showToast('Removed', 'Interface template deleted', 'success');
  7749. loadDynamicRouting();
  7750. } catch (err) {
  7751. showToast('Error', err.message, 'error');
  7752. }
  7753. }
  7754. async function enableSelectedOspfTemplate() {
  7755. const id = state.selectedOspfRow?.templates;
  7756. if (!id) return;
  7757. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  7758. method: 'POST',
  7759. headers: { 'Content-Type': 'application/json' },
  7760. body: JSON.stringify({ disabled: false })
  7761. });
  7762. loadDynamicRouting();
  7763. }
  7764. async function disableSelectedOspfTemplate() {
  7765. const id = state.selectedOspfRow?.templates;
  7766. if (!id) return;
  7767. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  7768. method: 'POST',
  7769. headers: { 'Content-Type': 'application/json' },
  7770. body: JSON.stringify({ disabled: true })
  7771. });
  7772. loadDynamicRouting();
  7773. }
  7774. async function removeSelectedOspfTemplate() {
  7775. const id = state.selectedOspfRow?.templates;
  7776. if (!id) return;
  7777. if (!confirm('Delete selected interface template?')) return;
  7778. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7779. loadDynamicRouting();
  7780. }
  7781. async function promptCommentOspfTemplate() {
  7782. const id = state.selectedOspfRow?.templates;
  7783. if (!id) return;
  7784. const tmpl = (state.ospfTemplates || []).find(t => t.id === id);
  7785. if (!tmpl) return;
  7786. const comment = prompt('Enter comment for template:', tmpl.comment || '');
  7787. if (comment === null) return;
  7788. tmpl.comment = comment;
  7789. await fetch(`${API_BASE}/routing/ospf/templates`, {
  7790. method: 'POST',
  7791. headers: { 'Content-Type': 'application/json' },
  7792. body: JSON.stringify(tmpl)
  7793. });
  7794. loadDynamicRouting();
  7795. }
  7796. // --- 5. OSPF STATIC NEIGHBOR ---
  7797. function populateStaticNbrAreaDropdowns() {
  7798. const select = document.getElementById('modal-ospf-snbr-area');
  7799. if (select) {
  7800. const cur = select.value;
  7801. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  7802. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  7803. if (cur) select.value = cur;
  7804. }
  7805. }
  7806. function openOspfStaticNbrModal(id = null) {
  7807. const isEdit = !!id;
  7808. populateStaticNbrAreaDropdowns();
  7809. const nbr = (state.ospfStaticNbrs || []).find(n => n.id === id) || {
  7810. id: '',
  7811. address: '',
  7812. area: 'Default',
  7813. poll_interval: 120,
  7814. cost: 1,
  7815. disabled: false,
  7816. comment: ''
  7817. };
  7818. document.getElementById('ospf-static-nbr-modal-title').innerText = isEdit ? nbr.address : 'New...';
  7819. document.getElementById('modal-ospf-snbr-id').value = isEdit ? nbr.id : '';
  7820. document.getElementById('modal-ospf-snbr-enabled').checked = !nbr.disabled;
  7821. document.getElementById('modal-ospf-snbr-comment').value = nbr.comment || '';
  7822. document.getElementById('modal-ospf-snbr-address').value = nbr.address || '';
  7823. document.getElementById('modal-ospf-snbr-area').value = nbr.area || 'Default';
  7824. document.getElementById('modal-ospf-snbr-poll').value = nbr.poll_interval || 120;
  7825. document.getElementById('modal-ospf-snbr-cost').value = nbr.cost || 1;
  7826. const btnRem = document.getElementById('btn-ospf-snbr-modal-remove');
  7827. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  7828. document.getElementById('ospf-static-nbr-modal').classList.remove('hidden');
  7829. }
  7830. function openEditOspfStaticNbrModal(id) {
  7831. openOspfStaticNbrModal(id);
  7832. }
  7833. function closeOspfStaticNbrModal() {
  7834. document.getElementById('ospf-static-nbr-modal').classList.add('hidden');
  7835. }
  7836. async function submitOspfStaticNbr(e) {
  7837. if (e) e.preventDefault();
  7838. const payload = {
  7839. id: document.getElementById('modal-ospf-snbr-id').value,
  7840. address: document.getElementById('modal-ospf-snbr-address').value.trim(),
  7841. area: document.getElementById('modal-ospf-snbr-area').value,
  7842. poll_interval: parseInt(document.getElementById('modal-ospf-snbr-poll').value, 10) || 120,
  7843. cost: parseInt(document.getElementById('modal-ospf-snbr-cost').value, 10) || 1,
  7844. disabled: !document.getElementById('modal-ospf-snbr-enabled').checked,
  7845. comment: document.getElementById('modal-ospf-snbr-comment').value.trim()
  7846. };
  7847. try {
  7848. const res = await fetch(`${API_BASE}/routing/ospf/static-neighbors`, {
  7849. method: 'POST',
  7850. headers: { 'Content-Type': 'application/json' },
  7851. body: JSON.stringify(payload)
  7852. });
  7853. if (res.ok) {
  7854. closeOspfStaticNbrModal();
  7855. showToast('Saved', 'Static neighbor saved', 'success');
  7856. loadDynamicRouting();
  7857. } else {
  7858. const err = await res.json();
  7859. showToast('Error', err.error || 'Failed to save static neighbor', 'error');
  7860. }
  7861. } catch (err) {
  7862. showToast('Error', err.message, 'error');
  7863. }
  7864. }
  7865. function applyOspfStaticNbrForm() {
  7866. submitOspfStaticNbr(null);
  7867. }
  7868. async function deleteCurrentOspfStaticNbr() {
  7869. const id = document.getElementById('modal-ospf-snbr-id').value;
  7870. if (!id) return;
  7871. if (!confirm('Delete this static neighbor?')) return;
  7872. try {
  7873. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7874. closeOspfStaticNbrModal();
  7875. showToast('Removed', 'Static neighbor removed', 'success');
  7876. loadDynamicRouting();
  7877. } catch (err) {
  7878. showToast('Error', err.message, 'error');
  7879. }
  7880. }
  7881. async function enableSelectedOspfStaticNbr() {
  7882. const id = state.selectedOspfRow?.['static-nbrs'];
  7883. if (!id) return;
  7884. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  7885. if (!n) return;
  7886. n.disabled = false;
  7887. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  7888. loadDynamicRouting();
  7889. }
  7890. async function disableSelectedOspfStaticNbr() {
  7891. const id = state.selectedOspfRow?.['static-nbrs'];
  7892. if (!id) return;
  7893. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  7894. if (!n) return;
  7895. n.disabled = true;
  7896. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  7897. loadDynamicRouting();
  7898. }
  7899. async function removeSelectedOspfStaticNbr() {
  7900. const id = state.selectedOspfRow?.['static-nbrs'];
  7901. if (!id) return;
  7902. if (!confirm('Delete selected static neighbor?')) return;
  7903. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7904. loadDynamicRouting();
  7905. }
  7906. async function promptCommentOspfStaticNbr() {
  7907. const id = state.selectedOspfRow?.['static-nbrs'];
  7908. if (!id) return;
  7909. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  7910. if (!n) return;
  7911. const comment = prompt('Enter comment for static neighbor:', n.comment || '');
  7912. if (comment === null) return;
  7913. n.comment = comment;
  7914. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  7915. loadDynamicRouting();
  7916. }
  7917. // Backward-compat aliases
  7918. function openAddOspfInterfaceModal() { openOspfTemplateModal(); }
  7919. function openEditOspfInterfaceModal(id) { openEditOspfTemplateModal(id); }
  7920. function closeOspfInterfaceModal() { closeOspfTemplateModal(); }
  7921. function submitOspfInterface(e) { submitOspfTemplate(e); }
  7922. function deleteOspfInterface(id) {
  7923. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  7924. }
  7925. function toggleOspfInterfaceState(id, disabled) {
  7926. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  7927. method: 'POST',
  7928. headers: { 'Content-Type': 'application/json' },
  7929. body: JSON.stringify({ disabled })
  7930. }).then(() => loadDynamicRouting());
  7931. }
  7932. function openAddOspfAreaModal() { openOspfAreaModal(); }
  7933. function deleteOspfArea(id) {
  7934. fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  7935. }
  7936. // ============================================================================
  7937. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  7938. // ============================================================================
  7939. function switchBridgeSubTab(tab) {
  7940. state.bridgeSubTab = tab;
  7941. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  7942. tabs.forEach(t => {
  7943. const panel = document.getElementById(`bridge-subtab-${t}`);
  7944. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  7945. if (panel) {
  7946. if (t === tab) panel.classList.remove('hidden');
  7947. else panel.classList.add('hidden');
  7948. }
  7949. if (btn) {
  7950. if (t === tab) {
  7951. 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';
  7952. } else {
  7953. 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';
  7954. }
  7955. }
  7956. });
  7957. const addBtn = document.getElementById('bridge-top-action-btn');
  7958. if (addBtn) {
  7959. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  7960. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  7961. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  7962. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  7963. }
  7964. if (tab === 'hosts') loadBridgeHosts();
  7965. setTimeout(initTableSorting, 50);
  7966. }
  7967. function openCurrentBridgeModal() {
  7968. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  7969. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  7970. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  7971. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  7972. }
  7973. async function loadBridge() {
  7974. try {
  7975. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vlanIfacesRes] = await Promise.all([
  7976. fetch(`${API_BASE}/bridge/bridges`),
  7977. fetch(`${API_BASE}/bridge/ports`),
  7978. fetch(`${API_BASE}/bridge/vlans`),
  7979. fetch(`${API_BASE}/bridge/summary`),
  7980. fetch(`${API_BASE}/vpn/eoip`),
  7981. fetch(`${API_BASE}/vlans`)
  7982. ]);
  7983. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  7984. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  7985. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  7986. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  7987. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  7988. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  7989. // Badges & Stats
  7990. const bBridges = document.getElementById('bridge-badge-bridges');
  7991. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  7992. const bPorts = document.getElementById('bridge-badge-ports');
  7993. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  7994. const bVlans = document.getElementById('bridge-badge-vlans');
  7995. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  7996. const bHosts = document.getElementById('bridge-badge-hosts');
  7997. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  7998. const sBr = document.getElementById('bridge-stat-bridges');
  7999. if (sBr) sBr.innerText = (state.bridges || []).length;
  8000. const sPorts = document.getElementById('bridge-stat-ports');
  8001. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  8002. const sHosts = document.getElementById('bridge-stat-hosts');
  8003. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  8004. renderBridges();
  8005. renderBridgePorts();
  8006. renderBridgeVLANs();
  8007. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  8008. } catch (err) {
  8009. console.error('Failed to load bridge subsystem:', err);
  8010. }
  8011. }
  8012. // ----------------- Bridges -----------------
  8013. function renderBridges() {
  8014. const tbody = document.getElementById('bridge-table-body');
  8015. const empty = document.getElementById('bridge-empty-bridges');
  8016. const countBadge = document.getElementById('bridge-count-badge');
  8017. if (!tbody) return;
  8018. tbody.innerHTML = '';
  8019. const bridges = state.bridges || [];
  8020. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  8021. if (bridges.length === 0) {
  8022. empty?.classList.remove('hidden');
  8023. return;
  8024. }
  8025. empty?.classList.add('hidden');
  8026. bridges.forEach((b, idx) => {
  8027. const tr = document.createElement('tr');
  8028. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  8029. // Format IP addresses pill list
  8030. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  8031. if (b.ip_addresses && b.ip_addresses.length > 0) {
  8032. ipsHtml = b.ip_addresses.map(ip => `
  8033. <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">
  8034. <span>${ip}</span>
  8035. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  8036. </span>
  8037. `).join(' ');
  8038. }
  8039. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  8040. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  8041. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  8042. tr.innerHTML = `
  8043. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  8044. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  8045. <td class="py-2.5 px-3 font-bold text-white text-sm">
  8046. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  8047. </td>
  8048. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  8049. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  8050. <td class="py-2.5 px-3">
  8051. <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>
  8052. </td>
  8053. <td class="py-2.5 px-3 text-center">
  8054. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  8055. </td>
  8056. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  8057. <td class="py-2.5 px-3">
  8058. <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>
  8059. </td>
  8060. <td class="py-2.5 px-3">
  8061. <div class="flex items-center gap-1.5 flex-wrap">
  8062. ${ipsHtml}
  8063. <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>
  8064. </div>
  8065. </td>
  8066. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  8067. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  8068. </td>
  8069. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  8070. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  8071. <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>
  8072. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  8073. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  8074. </td>
  8075. `;
  8076. tbody.appendChild(tr);
  8077. });
  8078. }
  8079. function openAddBridgeModal() {
  8080. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  8081. document.getElementById('bridge-modal-id').value = '';
  8082. document.getElementById('bridge-modal-name').value = 'bridge1';
  8083. document.getElementById('bridge-modal-name').disabled = false;
  8084. document.getElementById('bridge-modal-mtu').value = '1500';
  8085. document.getElementById('bridge-modal-mac').value = '';
  8086. document.getElementById('bridge-modal-stp').value = 'rstp';
  8087. document.getElementById('bridge-modal-priority').value = '32768';
  8088. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  8089. document.getElementById('bridge-modal-pvid').value = '1';
  8090. document.getElementById('bridge-modal-fastforward').checked = true;
  8091. document.getElementById('bridge-modal-comment').value = '';
  8092. document.getElementById('bridge-modal-disabled').checked = false;
  8093. toggleBridgeModalVlanFiltering();
  8094. document.getElementById('bridge-modal').classList.remove('hidden');
  8095. }
  8096. function openEditBridgeModal(id) {
  8097. const b = (state.bridges || []).find(x => x.id === id);
  8098. if (!b) return;
  8099. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  8100. document.getElementById('bridge-modal-id').value = b.id;
  8101. document.getElementById('bridge-modal-name').value = b.name;
  8102. document.getElementById('bridge-modal-name').disabled = true;
  8103. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  8104. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  8105. document.getElementById('bridge-modal-stp').value = b.stp || 'rstp';
  8106. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  8107. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  8108. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  8109. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  8110. document.getElementById('bridge-modal-comment').value = b.comment || '';
  8111. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  8112. toggleBridgeModalVlanFiltering();
  8113. document.getElementById('bridge-modal').classList.remove('hidden');
  8114. }
  8115. function closeBridgeModal() {
  8116. document.getElementById('bridge-modal').classList.add('hidden');
  8117. }
  8118. function toggleBridgeModalVlanFiltering() {
  8119. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  8120. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  8121. if (pvidBox) {
  8122. if (chk) pvidBox.classList.remove('opacity-40');
  8123. else pvidBox.classList.add('opacity-40');
  8124. }
  8125. }
  8126. async function submitSaveBridge(e) {
  8127. e.preventDefault();
  8128. const id = document.getElementById('bridge-modal-id').value;
  8129. const name = document.getElementById('bridge-modal-name').value.trim();
  8130. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  8131. const mac = document.getElementById('bridge-modal-mac').value.trim();
  8132. const stp = document.getElementById('bridge-modal-stp').value;
  8133. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  8134. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  8135. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  8136. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  8137. const comment = document.getElementById('bridge-modal-comment').value.trim();
  8138. const disabled = document.getElementById('bridge-modal-disabled').checked;
  8139. try {
  8140. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  8141. method: 'POST',
  8142. headers: { 'Content-Type': 'application/json' },
  8143. body: JSON.stringify({
  8144. id,
  8145. name,
  8146. mtu,
  8147. mac_address: mac,
  8148. stp,
  8149. priority,
  8150. vlan_filtering: vlanFiltering,
  8151. pvid,
  8152. fast_forward: fastForward,
  8153. comment,
  8154. disabled
  8155. })
  8156. });
  8157. if (res.ok) {
  8158. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  8159. closeBridgeModal();
  8160. loadBridge();
  8161. fetchData(false);
  8162. } else {
  8163. const err = await res.json();
  8164. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  8165. }
  8166. } catch (err) {
  8167. showToast('Error', err.message, 'error');
  8168. }
  8169. }
  8170. async function toggleBridgeState(id, disabled) {
  8171. try {
  8172. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  8173. method: 'POST',
  8174. headers: { 'Content-Type': 'application/json' },
  8175. body: JSON.stringify({ disabled })
  8176. });
  8177. if (res.ok) {
  8178. loadBridge();
  8179. fetchData(false);
  8180. }
  8181. } catch (err) {
  8182. showToast('Error', err.message, 'error');
  8183. }
  8184. }
  8185. async function deleteBridge(id) {
  8186. const b = (state.bridges || []).find(x => x.id === id);
  8187. const name = b ? b.name : id;
  8188. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  8189. try {
  8190. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8191. if (res.ok) {
  8192. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  8193. loadBridge();
  8194. fetchData(false);
  8195. } else {
  8196. const err = await res.json();
  8197. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  8198. }
  8199. } catch (err) {
  8200. showToast('Error', err.message, 'error');
  8201. }
  8202. }
  8203. // ----------------- Bridge IP Assignments -----------------
  8204. function openAddBridgeIPModal(id, name) {
  8205. document.getElementById('bridge-ip-modal-id').value = id;
  8206. document.getElementById('bridge-ip-modal-sub').innerText = name;
  8207. document.getElementById('bridge-ip-modal-cidr').value = '';
  8208. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  8209. }
  8210. function closeBridgeIPModal() {
  8211. document.getElementById('bridge-ip-modal').classList.add('hidden');
  8212. }
  8213. async function submitAddBridgeIP(e) {
  8214. e.preventDefault();
  8215. const id = document.getElementById('bridge-ip-modal-id').value;
  8216. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  8217. try {
  8218. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  8219. method: 'POST',
  8220. headers: { 'Content-Type': 'application/json' },
  8221. body: JSON.stringify({ ip })
  8222. });
  8223. if (res.ok) {
  8224. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  8225. closeBridgeIPModal();
  8226. loadBridge();
  8227. fetchData(false);
  8228. } else {
  8229. const err = await res.json();
  8230. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  8231. }
  8232. } catch (err) {
  8233. showToast('Error', err.message, 'error');
  8234. }
  8235. }
  8236. async function deleteBridgeIP(id, ip) {
  8237. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  8238. try {
  8239. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  8240. method: 'DELETE',
  8241. headers: { 'Content-Type': 'application/json' },
  8242. body: JSON.stringify({ ip })
  8243. });
  8244. if (res.ok) {
  8245. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  8246. loadBridge();
  8247. fetchData(false);
  8248. }
  8249. } catch (err) {
  8250. showToast('Error', err.message, 'error');
  8251. }
  8252. }
  8253. // ----------------- Bridge Ports -----------------
  8254. function renderBridgePorts() {
  8255. const tbody = document.getElementById('bridge-ports-table-body');
  8256. const empty = document.getElementById('bridge-empty-ports');
  8257. const countBadge = document.getElementById('bridge-ports-count-badge');
  8258. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  8259. if (!tbody) return;
  8260. tbody.innerHTML = '';
  8261. // Update filter select
  8262. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  8263. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  8264. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  8265. if (ports.length === 0) {
  8266. empty?.classList.remove('hidden');
  8267. return;
  8268. }
  8269. empty?.classList.add('hidden');
  8270. ports.forEach((p, idx) => {
  8271. const tr = document.createElement('tr');
  8272. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  8273. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  8274. tr.innerHTML = `
  8275. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  8276. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  8277. <td class="py-2.5 px-3 font-bold text-white text-sm">
  8278. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  8279. </td>
  8280. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  8281. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  8282. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  8283. <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>
  8284. <td class="py-2.5 px-3">
  8285. ${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>'}
  8286. </td>
  8287. <td class="py-2.5 px-3">
  8288. <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>
  8289. </td>
  8290. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  8291. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  8292. <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>
  8293. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  8294. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  8295. </td>
  8296. `;
  8297. tbody.appendChild(tr);
  8298. });
  8299. }
  8300. function openAddBridgePortModal() {
  8301. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  8302. document.getElementById('bridge-port-modal-id').value = '';
  8303. populateBridgeSelect('bridge-port-modal-bridge');
  8304. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  8305. document.getElementById('bridge-port-modal-pvid').value = '1';
  8306. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  8307. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  8308. document.getElementById('bridge-port-modal-horizon').value = '0';
  8309. document.getElementById('bridge-port-modal-pathcost').value = '10';
  8310. document.getElementById('bridge-port-modal-priority').value = '128';
  8311. document.getElementById('bridge-port-modal-learn').checked = true;
  8312. document.getElementById('bridge-port-modal-comment').value = '';
  8313. document.getElementById('bridge-port-modal-disabled').checked = false;
  8314. document.getElementById('bridge-port-modal').classList.remove('hidden');
  8315. }
  8316. function openEditBridgePortModal(id) {
  8317. const p = (state.bridgePorts || []).find(x => x.id === id);
  8318. if (!p) return;
  8319. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  8320. document.getElementById('bridge-port-modal-id').value = p.id;
  8321. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  8322. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  8323. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  8324. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  8325. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  8326. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  8327. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  8328. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  8329. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  8330. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  8331. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  8332. document.getElementById('bridge-port-modal').classList.remove('hidden');
  8333. }
  8334. function closeBridgePortModal() {
  8335. document.getElementById('bridge-port-modal').classList.add('hidden');
  8336. }
  8337. async function submitSaveBridgePort(e) {
  8338. e.preventDefault();
  8339. const id = document.getElementById('bridge-port-modal-id').value;
  8340. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  8341. const iface = document.getElementById('bridge-port-modal-interface').value;
  8342. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  8343. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  8344. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  8345. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  8346. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  8347. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  8348. const learn = document.getElementById('bridge-port-modal-learn').checked;
  8349. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  8350. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  8351. try {
  8352. const res = await fetch(`${API_BASE}/bridge/ports`, {
  8353. method: 'POST',
  8354. headers: { 'Content-Type': 'application/json' },
  8355. body: JSON.stringify({
  8356. id,
  8357. bridge,
  8358. interface: iface,
  8359. pvid,
  8360. frame_types: frameTypes,
  8361. ingress_filtering: ingressFiltering,
  8362. horizon,
  8363. path_cost: pathCost,
  8364. priority,
  8365. learn,
  8366. comment,
  8367. disabled
  8368. })
  8369. });
  8370. if (res.ok) {
  8371. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  8372. closeBridgePortModal();
  8373. loadBridge();
  8374. fetchData(false);
  8375. } else {
  8376. const err = await res.json();
  8377. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  8378. }
  8379. } catch (err) {
  8380. showToast('Error', err.message, 'error');
  8381. }
  8382. }
  8383. async function toggleBridgePortState(id, disabled) {
  8384. try {
  8385. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  8386. method: 'POST',
  8387. headers: { 'Content-Type': 'application/json' },
  8388. body: JSON.stringify({ disabled })
  8389. });
  8390. if (res.ok) {
  8391. loadBridge();
  8392. fetchData(false);
  8393. }
  8394. } catch (err) {
  8395. showToast('Error', err.message, 'error');
  8396. }
  8397. }
  8398. async function deleteBridgePort(id) {
  8399. const p = (state.bridgePorts || []).find(x => x.id === id);
  8400. const iface = p ? p.interface : id;
  8401. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  8402. try {
  8403. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8404. if (res.ok) {
  8405. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  8406. loadBridge();
  8407. fetchData(false);
  8408. }
  8409. } catch (err) {
  8410. showToast('Error', err.message, 'error');
  8411. }
  8412. }
  8413. // ----------------- Bridge VLANs -----------------
  8414. function renderBridgeVLANs() {
  8415. const tbody = document.getElementById('bridge-vlans-table-body');
  8416. const empty = document.getElementById('bridge-empty-vlans');
  8417. const countBadge = document.getElementById('bridge-vlans-count-badge');
  8418. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  8419. if (!tbody) return;
  8420. tbody.innerHTML = '';
  8421. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  8422. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  8423. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  8424. if (vlans.length === 0) {
  8425. empty?.classList.remove('hidden');
  8426. return;
  8427. }
  8428. empty?.classList.add('hidden');
  8429. vlans.forEach((v, idx) => {
  8430. const tr = document.createElement('tr');
  8431. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  8432. const taggedHtml = (v.tagged && v.tagged.length > 0)
  8433. ? 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(' ')
  8434. : '<span class="text-slate-600">none</span>';
  8435. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  8436. ? 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(' ')
  8437. : '<span class="text-slate-600">none</span>';
  8438. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  8439. tr.innerHTML = `
  8440. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  8441. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  8442. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  8443. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  8444. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  8445. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  8446. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  8447. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  8448. <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>
  8449. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  8450. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  8451. </td>
  8452. `;
  8453. tbody.appendChild(tr);
  8454. });
  8455. }
  8456. function openAddBridgeVLANModal() {
  8457. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  8458. document.getElementById('bridge-vlan-modal-id').value = '';
  8459. populateBridgeSelect('bridge-vlan-modal-bridge');
  8460. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  8461. document.getElementById('bridge-vlan-modal-comment').value = '';
  8462. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  8463. updateBridgeVlanPortCheckboxes();
  8464. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  8465. }
  8466. function openEditBridgeVLANModal(id) {
  8467. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  8468. if (!v) return;
  8469. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  8470. document.getElementById('bridge-vlan-modal-id').value = v.id;
  8471. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  8472. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  8473. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  8474. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  8475. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  8476. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  8477. }
  8478. function closeBridgeVlanModal() {
  8479. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  8480. }
  8481. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  8482. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  8483. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  8484. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  8485. if (!taggedBox || !untaggedBox) return;
  8486. // Ports belonging to the selected bridge
  8487. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  8488. if (memberPorts.length === 0) {
  8489. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  8490. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  8491. return;
  8492. }
  8493. taggedBox.innerHTML = memberPorts.map(p => `
  8494. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  8495. <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">
  8496. <span>${p.interface}</span>
  8497. </label>
  8498. `).join('');
  8499. untaggedBox.innerHTML = memberPorts.map(p => `
  8500. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  8501. <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">
  8502. <span>${p.interface}</span>
  8503. </label>
  8504. `).join('');
  8505. }
  8506. async function submitSaveBridgeVLAN(e) {
  8507. e.preventDefault();
  8508. const id = document.getElementById('bridge-vlan-modal-id').value;
  8509. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  8510. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  8511. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  8512. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  8513. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  8514. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  8515. try {
  8516. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  8517. method: 'POST',
  8518. headers: { 'Content-Type': 'application/json' },
  8519. body: JSON.stringify({
  8520. id,
  8521. bridge,
  8522. vlan_ids: vlanIDs,
  8523. tagged,
  8524. untagged,
  8525. comment,
  8526. disabled
  8527. })
  8528. });
  8529. if (res.ok) {
  8530. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  8531. closeBridgeVlanModal();
  8532. loadBridge();
  8533. } else {
  8534. const err = await res.json();
  8535. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  8536. }
  8537. } catch (err) {
  8538. showToast('Error', err.message, 'error');
  8539. }
  8540. }
  8541. async function toggleBridgeVLANState(id, disabled) {
  8542. try {
  8543. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  8544. method: 'POST',
  8545. headers: { 'Content-Type': 'application/json' },
  8546. body: JSON.stringify({ disabled })
  8547. });
  8548. if (res.ok) loadBridge();
  8549. } catch (err) {
  8550. showToast('Error', err.message, 'error');
  8551. }
  8552. }
  8553. async function deleteBridgeVLAN(id) {
  8554. if (!confirm('Delete this bridge VLAN entry?')) return;
  8555. try {
  8556. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8557. if (res.ok) {
  8558. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  8559. loadBridge();
  8560. }
  8561. } catch (err) {
  8562. showToast('Error', err.message, 'error');
  8563. }
  8564. }
  8565. // ----------------- Hosts / MAC Table -----------------
  8566. async function loadBridgeHosts() {
  8567. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  8568. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  8569. try {
  8570. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  8571. const res = await fetch(url);
  8572. if (res.ok) {
  8573. state.bridgeHosts = await res.json();
  8574. renderBridgeHosts();
  8575. }
  8576. } catch (err) {
  8577. console.error('Failed to load bridge hosts:', err);
  8578. }
  8579. }
  8580. function renderBridgeHosts() {
  8581. const tbody = document.getElementById('bridge-hosts-table-body');
  8582. const empty = document.getElementById('bridge-empty-hosts');
  8583. const countBadge = document.getElementById('bridge-hosts-count-badge');
  8584. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  8585. if (!tbody) return;
  8586. tbody.innerHTML = '';
  8587. const hosts = (state.bridgeHosts || []).filter(h => {
  8588. if (!search) return true;
  8589. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  8590. });
  8591. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  8592. if (hosts.length === 0) {
  8593. empty?.classList.remove('hidden');
  8594. return;
  8595. }
  8596. empty?.classList.add('hidden');
  8597. hosts.forEach(h => {
  8598. const tr = document.createElement('tr');
  8599. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  8600. let flagBadges = '';
  8601. 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>';
  8602. 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>';
  8603. 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>';
  8604. tr.innerHTML = `
  8605. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  8606. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  8607. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  8608. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  8609. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  8610. <td class="py-2.5 px-3">${flagBadges}</td>
  8611. `;
  8612. tbody.appendChild(tr);
  8613. });
  8614. }
  8615. async function flushBridgeHosts() {
  8616. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  8617. if (!selBridge) {
  8618. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  8619. return;
  8620. }
  8621. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  8622. try {
  8623. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  8624. method: 'POST',
  8625. headers: { 'Content-Type': 'application/json' },
  8626. body: JSON.stringify({ bridge: selBridge })
  8627. });
  8628. if (res.ok) {
  8629. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  8630. loadBridgeHosts();
  8631. }
  8632. } catch (err) {
  8633. showToast('Error', err.message, 'error');
  8634. }
  8635. }
  8636. // ----------------- Helpers -----------------
  8637. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  8638. const sel = document.getElementById(selectId);
  8639. if (!sel) return;
  8640. const prevVal = currentVal || sel.value;
  8641. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  8642. (state.bridges || []).forEach(b => {
  8643. const opt = document.createElement('option');
  8644. opt.value = b.name;
  8645. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  8646. if (b.name === prevVal) opt.selected = true;
  8647. sel.appendChild(opt);
  8648. });
  8649. }
  8650. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  8651. const sel = document.getElementById(selectId);
  8652. if (!sel) return;
  8653. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  8654. // 1. Physical Interfaces
  8655. const grpPhys = document.createElement('optgroup');
  8656. grpPhys.label = 'Physical Interfaces';
  8657. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  8658. const opt = document.createElement('option');
  8659. opt.value = i.name;
  8660. opt.innerText = `${i.name} (${i.role || i.type})`;
  8661. if (i.name === currentVal) opt.selected = true;
  8662. grpPhys.appendChild(opt);
  8663. });
  8664. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  8665. // 2. VLAN Sub-interfaces
  8666. const grpVlans = document.createElement('optgroup');
  8667. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  8668. (state.vlans || []).forEach(v => {
  8669. const opt = document.createElement('option');
  8670. opt.value = v.name;
  8671. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  8672. if (v.name === currentVal) opt.selected = true;
  8673. grpVlans.appendChild(opt);
  8674. });
  8675. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  8676. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  8677. const grpEoip = document.createElement('optgroup');
  8678. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  8679. (state.eoipTunnels || []).forEach(t => {
  8680. const opt = document.createElement('option');
  8681. opt.value = t.name;
  8682. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  8683. if (t.name === currentVal) opt.selected = true;
  8684. grpEoip.appendChild(opt);
  8685. });
  8686. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  8687. }
  8688. // -------------------------------------------------------------
  8689. // RouterOS v7 Routing Filters Management (/routing filter)
  8690. // -------------------------------------------------------------
  8691. if (!state.activeRoutingFilterTab) state.activeRoutingFilterTab = 'rules';
  8692. if (!state.selectedFilterRow) state.selectedFilterRow = {};
  8693. if (!state.rfSort) state.rfSort = {};
  8694. function switchRoutingFilterTab(tab) {
  8695. state.activeRoutingFilterTab = tab;
  8696. const tabs = ['rules', 'select-rules', 'community-lists', 'as-lists'];
  8697. tabs.forEach(t => {
  8698. const btn = document.getElementById(`tab-rf-${t}`);
  8699. const content = document.getElementById(`tab-content-rf-${t}`);
  8700. if (btn) {
  8701. if (t === tab) {
  8702. btn.className = 'px-3 py-1 text-xs font-semibold rounded bg-emerald-600/20 text-emerald-300 border border-emerald-500/30 transition shadow-sm';
  8703. } else {
  8704. btn.className = 'px-3 py-1 text-xs font-semibold rounded text-slate-400 hover:text-white hover:bg-slate-800 transition';
  8705. }
  8706. }
  8707. if (content) {
  8708. if (t === tab) content.classList.remove('hidden');
  8709. else content.classList.add('hidden');
  8710. }
  8711. });
  8712. const chainContainer = document.getElementById('rf-chain-filter-container');
  8713. if (chainContainer) {
  8714. if (tab === 'rules' || tab === 'select-rules') chainContainer.classList.remove('hidden');
  8715. else chainContainer.classList.add('hidden');
  8716. }
  8717. renderRoutingFilters();
  8718. }
  8719. function selectFilterRow(tab, id) {
  8720. if (state.selectedFilterRow[tab] === id) {
  8721. delete state.selectedFilterRow[tab];
  8722. } else {
  8723. state.selectedFilterRow[tab] = id;
  8724. }
  8725. if (tab === 'rules') renderRoutingFilterRules();
  8726. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  8727. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  8728. else if (tab === 'as-lists') renderRoutingFilterASLists();
  8729. }
  8730. function openRoutingFilterNewModal() {
  8731. const tab = state.activeRoutingFilterTab || 'rules';
  8732. if (tab === 'rules') openAddRoutingFilterModal();
  8733. else if (tab === 'select-rules') openAddSelectRuleModal();
  8734. else if (tab === 'community-lists') openAddCommunityListModal();
  8735. else if (tab === 'as-lists') openAddASListModal();
  8736. }
  8737. function toggleSelectedRoutingFilter(disabled) {
  8738. const tab = state.activeRoutingFilterTab || 'rules';
  8739. const id = state.selectedFilterRow[tab];
  8740. if (!id) {
  8741. showToast('Select Row', 'Please click on a row to select it first', 'info');
  8742. return;
  8743. }
  8744. if (tab === 'rules') toggleRoutingFilterState(id, disabled);
  8745. else if (tab === 'select-rules') toggleSelectRuleState(id, disabled);
  8746. else if (tab === 'community-lists') toggleCommunityListState(id, disabled);
  8747. else if (tab === 'as-lists') toggleASListState(id, disabled);
  8748. }
  8749. function removeSelectedRoutingFilter() {
  8750. const tab = state.activeRoutingFilterTab || 'rules';
  8751. const id = state.selectedFilterRow[tab];
  8752. if (!id) {
  8753. showToast('Select Row', 'Please click on a row to select it first', 'info');
  8754. return;
  8755. }
  8756. if (tab === 'rules') deleteRoutingFilter(id);
  8757. else if (tab === 'select-rules') deleteSelectRule(id);
  8758. else if (tab === 'community-lists') deleteCommunityList(id);
  8759. else if (tab === 'as-lists') deleteASList(id);
  8760. }
  8761. function searchRoutingFilters(q) {
  8762. state.rfSearchQuery = (q || '').trim().toLowerCase();
  8763. renderRoutingFilters();
  8764. }
  8765. function sortFilterTable(tab, col) {
  8766. if (!state.rfSort) state.rfSort = {};
  8767. if (!state.rfSort[tab]) state.rfSort[tab] = { col: col, asc: true };
  8768. if (state.rfSort[tab].col === col) {
  8769. state.rfSort[tab].asc = !state.rfSort[tab].asc;
  8770. } else {
  8771. state.rfSort[tab].col = col;
  8772. state.rfSort[tab].asc = true;
  8773. }
  8774. const asc = state.rfSort[tab].asc;
  8775. let list = [];
  8776. if (tab === 'rules') list = state.routingFilters || [];
  8777. else if (tab === 'select-rules') list = state.routingSelectRules || [];
  8778. else if (tab === 'community-lists') list = state.routingCommunityLists || [];
  8779. else if (tab === 'as-lists') list = state.routingASLists || [];
  8780. list.sort((a, b) => {
  8781. let valA = a[col] ?? '';
  8782. let valB = b[col] ?? '';
  8783. if (col === 'flags') {
  8784. valA = a.disabled ? 'X' : 'A';
  8785. valB = b.disabled ? 'X' : 'A';
  8786. }
  8787. if (typeof valA === 'number' && typeof valB === 'number') {
  8788. return asc ? valA - valB : valB - valA;
  8789. }
  8790. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  8791. });
  8792. const allCols = ['flags', 'rule_order', 'chain', 'rule', 'name', 'communities', 'range', 'regexp', 'comment'];
  8793. allCols.forEach(c => {
  8794. const el = document.getElementById(`sort-icon-${tab}-${c}`);
  8795. if (el) el.innerText = (c === col) ? (asc ? '▲' : '▼') : '';
  8796. });
  8797. if (tab === 'rules') renderRoutingFilterRules();
  8798. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  8799. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  8800. else if (tab === 'as-lists') renderRoutingFilterASLists();
  8801. }
  8802. function renderRoutingFilters() {
  8803. const navBadge = document.getElementById('badge-filters-count');
  8804. const allRules = state.routingFilters || [];
  8805. if (navBadge) navBadge.innerText = allRules.length;
  8806. // Populate chain filter select options and datalist
  8807. const chainSelect = document.getElementById('routing-filter-chain-select');
  8808. const chainDatalist = document.getElementById('dl-routing-chains');
  8809. const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
  8810. if (chainSelect) {
  8811. const currentVal = state.filterChainSelected || 'all';
  8812. chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
  8813. uniqueChains.map(ch => {
  8814. const count = allRules.filter(r => r.chain === ch).length;
  8815. return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
  8816. }).join('');
  8817. chainSelect.value = currentVal;
  8818. }
  8819. if (chainDatalist) {
  8820. chainDatalist.innerHTML = uniqueChains.map(ch => `<option value="${escapeHtml(ch)}">`).join('');
  8821. }
  8822. renderRoutingFilterRules();
  8823. renderRoutingFilterSelectRules();
  8824. renderRoutingFilterCommunityLists();
  8825. renderRoutingFilterASLists();
  8826. }
  8827. function filterRoutingFiltersByChain(chain) {
  8828. state.filterChainSelected = chain;
  8829. renderRoutingFilters();
  8830. }
  8831. // -------------------------------------------------------------
  8832. // TAB 1: RULES (/routing filter rule)
  8833. // -------------------------------------------------------------
  8834. function renderRoutingFilterRules() {
  8835. const tbody = document.getElementById('routing-filter-rules-tbody');
  8836. if (!tbody) return;
  8837. const empty = document.getElementById('rf-rules-empty');
  8838. const statusCount = document.getElementById('rf-status-count');
  8839. let list = (state.routingFilters || []).slice();
  8840. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  8841. list = list.filter(r => r.chain === state.filterChainSelected);
  8842. }
  8843. const q = state.rfSearchQuery;
  8844. if (q) {
  8845. list = list.filter(r =>
  8846. (r.chain && r.chain.toLowerCase().includes(q)) ||
  8847. (r.rule && r.rule.toLowerCase().includes(q)) ||
  8848. (r.prefix && r.prefix.toLowerCase().includes(q)) ||
  8849. (r.comment && r.comment.toLowerCase().includes(q))
  8850. );
  8851. }
  8852. if (!state.rfSort?.['rules']) {
  8853. list.sort((a, b) => {
  8854. if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
  8855. return (a.rule_order || 0) - (b.rule_order || 0);
  8856. });
  8857. }
  8858. if (statusCount && (state.activeRoutingFilterTab === 'rules' || !state.activeRoutingFilterTab)) {
  8859. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  8860. }
  8861. if (list.length === 0) {
  8862. tbody.innerHTML = '';
  8863. if (empty) empty.classList.remove('hidden');
  8864. return;
  8865. }
  8866. if (empty) empty.classList.add('hidden');
  8867. tbody.innerHTML = list.map(r => {
  8868. const isSelected = state.selectedFilterRow?.['rules'] === r.id;
  8869. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  8870. const flagX = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8871. const flagC = r.comment ? '<span class="text-amber-400 font-bold ml-1" title="Comment">C</span>' : '';
  8872. let ruleDisplay = '';
  8873. if (r.rule && r.rule.trim() !== '') {
  8874. ruleDisplay = `<span class="text-emerald-400 font-mono font-medium">${escapeHtml(r.rule)}</span>`;
  8875. } else {
  8876. let conds = [];
  8877. if (r.prefix) conds.push(`dst in ${escapeHtml(r.prefix)}`);
  8878. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${escapeHtml(r.match_protocol)}`);
  8879. let act = r.action || 'accept';
  8880. ruleDisplay = `<span class="text-slate-300 font-mono">if (${conds.length ? conds.join(' && ') : 'true'}) { ${escapeHtml(act)}; }</span>`;
  8881. }
  8882. return `
  8883. <tr onclick="selectFilterRow('rules', '${r.id}')" class="cursor-pointer transition select-none ${isSelected ? 'bg-emerald-950/40 ring-1 ring-emerald-500/40' : 'hover:bg-slate-800/40'}">
  8884. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}${flagC}</td>
  8885. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  8886. <td class="py-2 px-3">
  8887. <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>
  8888. </td>
  8889. <td class="py-2 px-3 break-all max-w-xl">${ruleDisplay}</td>
  8890. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  8891. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  8892. <button onclick="moveRoutingFilterOrder('${r.id}', -1)" title="Move Up" class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700">▲</button>
  8893. <button onclick="moveRoutingFilterOrder('${r.id}', 1)" title="Move Down" class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700">▼</button>
  8894. <button onclick="toggleRoutingFilterState('${r.id}', ${!r.disabled})" class="px-2 py-0.5 rounded text-[10px] ${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'}">
  8895. ${r.disabled ? 'Enable' : 'Disable'}
  8896. </button>
  8897. <button onclick="openEditRoutingFilterModal('${r.id}')" class="px-2 py-0.5 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-emerald-300 border border-slate-700">
  8898. Edit
  8899. </button>
  8900. <button onclick="deleteRoutingFilter('${r.id}')" class="px-2 py-0.5 rounded text-[10px] bg-rose-950/60 hover:bg-rose-900 text-rose-300 border border-rose-900/50">
  8901. ✕
  8902. </button>
  8903. </td>
  8904. </tr>
  8905. `;
  8906. }).join('');
  8907. }
  8908. // -------------------------------------------------------------
  8909. // TAB 2: SELECT RULES (/routing filter select-rule)
  8910. // -------------------------------------------------------------
  8911. function renderRoutingFilterSelectRules() {
  8912. const tbody = document.getElementById('routing-filter-select-rules-tbody');
  8913. if (!tbody) return;
  8914. const empty = document.getElementById('rf-select-rules-empty');
  8915. const statusCount = document.getElementById('rf-status-count');
  8916. let list = (state.routingSelectRules || []).slice();
  8917. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  8918. list = list.filter(r => r.chain === state.filterChainSelected);
  8919. }
  8920. const q = state.rfSearchQuery;
  8921. if (q) {
  8922. list = list.filter(r =>
  8923. (r.chain && r.chain.toLowerCase().includes(q)) ||
  8924. (r.rule && r.rule.toLowerCase().includes(q)) ||
  8925. (r.comment && r.comment.toLowerCase().includes(q))
  8926. );
  8927. }
  8928. if (statusCount && state.activeRoutingFilterTab === 'select-rules') {
  8929. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  8930. }
  8931. if (list.length === 0) {
  8932. tbody.innerHTML = '';
  8933. if (empty) empty.classList.remove('hidden');
  8934. return;
  8935. }
  8936. if (empty) empty.classList.add('hidden');
  8937. tbody.innerHTML = list.map(r => {
  8938. const isSelected = state.selectedFilterRow?.['select-rules'] === r.id;
  8939. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  8940. const flagX = r.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  8941. return `
  8942. <tr onclick="selectFilterRow('select-rules', '${r.id}')" class="cursor-pointer transition select-none ${isSelected ? 'bg-emerald-950/40 ring-1 ring-emerald-500/40' : 'hover:bg-slate-800/40'}">
  8943. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  8944. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  8945. <td class="py-2 px-3">
  8946. <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>
  8947. </td>
  8948. <td class="py-2 px-3 break-all max-w-xl font-mono text-emerald-400">${escapeHtml(r.rule || '')}</td>
  8949. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  8950. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  8951. <button onclick="toggleSelectRuleState('${r.id}', ${!r.disabled})" class="px-2 py-0.5 rounded text-[10px] ${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'}">
  8952. ${r.disabled ? 'Enable' : 'Disable'}
  8953. </button>
  8954. <button onclick="openEditSelectRuleModal('${r.id}')" class="px-2 py-0.5 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-emerald-300 border border-slate-700">
  8955. Edit
  8956. </button>
  8957. <button onclick="deleteSelectRule('${r.id}')" class="px-2 py-0.5 rounded text-[10px] bg-rose-950/60 hover:bg-rose-900 text-rose-300 border border-rose-900/50">
  8958. ✕
  8959. </button>
  8960. </td>
  8961. </tr>
  8962. `;
  8963. }).join('');
  8964. }
  8965. // -------------------------------------------------------------
  8966. // TAB 3: COMMUNITY LISTS (/routing filter community-list)
  8967. // -------------------------------------------------------------
  8968. function renderRoutingFilterCommunityLists() {
  8969. const tbody = document.getElementById('routing-filter-comm-lists-tbody');
  8970. if (!tbody) return;
  8971. const empty = document.getElementById('rf-comm-lists-empty');
  8972. const statusCount = document.getElementById('rf-status-count');
  8973. let list = (state.routingCommunityLists || []).slice();
  8974. const q = state.rfSearchQuery;
  8975. if (q) {
  8976. list = list.filter(cl =>
  8977. (cl.name && cl.name.toLowerCase().includes(q)) ||
  8978. (cl.comment && cl.comment.toLowerCase().includes(q)) ||
  8979. (cl.communities && cl.communities.some(c => c.toLowerCase().includes(q)))
  8980. );
  8981. }
  8982. if (statusCount && state.activeRoutingFilterTab === 'community-lists') {
  8983. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  8984. }
  8985. if (list.length === 0) {
  8986. tbody.innerHTML = '';
  8987. if (empty) empty.classList.remove('hidden');
  8988. return;
  8989. }
  8990. if (empty) empty.classList.add('hidden');
  8991. tbody.innerHTML = list.map(cl => {
  8992. const isSelected = state.selectedFilterRow?.['community-lists'] === cl.id;
  8993. const flagA = !cl.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  8994. const flagX = cl.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  8995. const commBadges = (cl.communities || []).map(c =>
  8996. `<span class="px-1.5 py-0.5 rounded text-[10px] bg-indigo-950 text-indigo-300 border border-indigo-800/40 font-mono">${escapeHtml(c)}</span>`
  8997. ).join(' ');
  8998. return `
  8999. <tr onclick="selectFilterRow('community-lists', '${cl.id}')" class="cursor-pointer transition select-none ${isSelected ? 'bg-emerald-950/40 ring-1 ring-emerald-500/40' : 'hover:bg-slate-800/40'}">
  9000. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  9001. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(cl.name)}</td>
  9002. <td class="py-2 px-3 space-x-1">${commBadges || '<span class="text-slate-600">-</span>'}</td>
  9003. <td class="py-2 px-3 font-mono text-slate-400">${escapeHtml(cl.regexp || '-')}</td>
  9004. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(cl.comment || '')}</td>
  9005. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  9006. <button onclick="toggleCommunityListState('${cl.id}', ${!cl.disabled})" class="px-2 py-0.5 rounded text-[10px] ${cl.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'}">
  9007. ${cl.disabled ? 'Enable' : 'Disable'}
  9008. </button>
  9009. <button onclick="openEditCommunityListModal('${cl.id}')" class="px-2 py-0.5 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-emerald-300 border border-slate-700">
  9010. Edit
  9011. </button>
  9012. <button onclick="deleteCommunityList('${cl.id}')" class="px-2 py-0.5 rounded text-[10px] bg-rose-950/60 hover:bg-rose-900 text-rose-300 border border-rose-900/50">
  9013. ✕
  9014. </button>
  9015. </td>
  9016. </tr>
  9017. `;
  9018. }).join('');
  9019. }
  9020. // -------------------------------------------------------------
  9021. // TAB 4: AS LISTS (/routing filter num-list)
  9022. // -------------------------------------------------------------
  9023. function renderRoutingFilterASLists() {
  9024. const tbody = document.getElementById('routing-filter-as-lists-tbody');
  9025. if (!tbody) return;
  9026. const empty = document.getElementById('rf-as-lists-empty');
  9027. const statusCount = document.getElementById('rf-status-count');
  9028. let list = (state.routingASLists || []).slice();
  9029. const q = state.rfSearchQuery;
  9030. if (q) {
  9031. list = list.filter(al =>
  9032. (al.name && al.name.toLowerCase().includes(q)) ||
  9033. (al.range && al.range.toLowerCase().includes(q)) ||
  9034. (al.comment && al.comment.toLowerCase().includes(q))
  9035. );
  9036. }
  9037. if (statusCount && state.activeRoutingFilterTab === 'as-lists') {
  9038. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  9039. }
  9040. if (list.length === 0) {
  9041. tbody.innerHTML = '';
  9042. if (empty) empty.classList.remove('hidden');
  9043. return;
  9044. }
  9045. if (empty) empty.classList.add('hidden');
  9046. tbody.innerHTML = list.map(al => {
  9047. const isSelected = state.selectedFilterRow?.['as-lists'] === al.id;
  9048. const flagA = !al.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  9049. const flagX = al.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  9050. return `
  9051. <tr onclick="selectFilterRow('as-lists', '${al.id}')" class="cursor-pointer transition select-none ${isSelected ? 'bg-emerald-950/40 ring-1 ring-emerald-500/40' : 'hover:bg-slate-800/40'}">
  9052. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  9053. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(al.name)}</td>
  9054. <td class="py-2 px-3 font-mono text-purple-300">${escapeHtml(al.range)}</td>
  9055. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(al.comment || '')}</td>
  9056. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  9057. <button onclick="toggleASListState('${al.id}', ${!al.disabled})" class="px-2 py-0.5 rounded text-[10px] ${al.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'}">
  9058. ${al.disabled ? 'Enable' : 'Disable'}
  9059. </button>
  9060. <button onclick="openEditASListModal('${al.id}')" class="px-2 py-0.5 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-emerald-300 border border-slate-700">
  9061. Edit
  9062. </button>
  9063. <button onclick="deleteASList('${al.id}')" class="px-2 py-0.5 rounded text-[10px] bg-rose-950/60 hover:bg-rose-900 text-rose-300 border border-rose-900/50">
  9064. ✕
  9065. </button>
  9066. </td>
  9067. </tr>
  9068. `;
  9069. }).join('');
  9070. }
  9071. // -------------------------------------------------------------
  9072. // SNIPPETS & WIZARD HELPERS
  9073. // -------------------------------------------------------------
  9074. function insertRuleSnippet(type) {
  9075. const textarea = document.getElementById('modal-rf-rule');
  9076. if (!textarea) return;
  9077. let snippet = '';
  9078. switch (type) {
  9079. case 'accept-default':
  9080. snippet = 'if (dst in 0.0.0.0/0) { accept; }';
  9081. break;
  9082. case 'drop-rfc1918':
  9083. snippet = 'if (dst in 10.0.0.0/8 || dst in 172.16.0.0/12 || dst in 192.168.0.0/16) { reject; }';
  9084. break;
  9085. case 'len-24':
  9086. snippet = 'if (dst-len > 24) { reject; }';
  9087. break;
  9088. case 'local-pref-150':
  9089. snippet = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  9090. break;
  9091. case 'as-prepend-2':
  9092. snippet = 'set bgp-path-prepend 2; accept;';
  9093. break;
  9094. case 'set-comm':
  9095. snippet = 'set bgp-communities.add 65000:100; accept;';
  9096. break;
  9097. case 'match-comm':
  9098. snippet = 'if (bgp-communities includes 65000:100) { accept; }';
  9099. break;
  9100. case 'reject-all':
  9101. snippet = 'reject;';
  9102. break;
  9103. }
  9104. if (!snippet) return;
  9105. if (!textarea.value.trim()) {
  9106. textarea.value = snippet;
  9107. } else {
  9108. textarea.value = textarea.value.trim() + '\n' + snippet;
  9109. }
  9110. }
  9111. function generateScriptFromWizard() {
  9112. const pfx = (document.getElementById('modal-rf-prefix')?.value || '').trim();
  9113. const pfxLen = (document.getElementById('modal-rf-prefix-len')?.value || '').trim();
  9114. const proto = document.getElementById('modal-rf-protocol')?.value || 'any';
  9115. const asp = (document.getElementById('modal-rf-as-path')?.value || '').trim();
  9116. const comm = (document.getElementById('modal-rf-community')?.value || '').trim();
  9117. const act = document.getElementById('modal-rf-action')?.value || 'accept';
  9118. const lp = parseInt(document.getElementById('modal-rf-set-local-pref')?.value, 10) || 0;
  9119. const prep = parseInt(document.getElementById('modal-rf-set-as-prepend')?.value, 10) || 0;
  9120. const conds = [];
  9121. if (pfx) {
  9122. if (pfxLen) {
  9123. if (pfxLen.includes('-')) {
  9124. const parts = pfxLen.split('-');
  9125. conds.push(`dst in ${pfx}{${parts[0].trim()},${parts[1].trim()}}`);
  9126. } else {
  9127. conds.push(`dst in ${pfx} && dst-len >= ${pfxLen}`);
  9128. }
  9129. } else {
  9130. conds.push(`dst in ${pfx}`);
  9131. }
  9132. }
  9133. if (proto && proto !== 'any') {
  9134. conds.push(`protocol ${proto}`);
  9135. }
  9136. if (asp) {
  9137. conds.push(`bgp-as-path "${asp}"`);
  9138. }
  9139. if (comm) {
  9140. conds.push(`bgp-communities includes ${comm}`);
  9141. }
  9142. const actions = [];
  9143. if (lp > 0) actions.push(`set bgp-local-pref ${lp};`);
  9144. if (prep > 0) actions.push(`set bgp-path-prepend ${prep};`);
  9145. actions.push(`${act};`);
  9146. let code = '';
  9147. if (conds.length > 0) {
  9148. code = `if (${conds.join(' && ')}) {\n ${actions.join(' ')}\n}`;
  9149. } else {
  9150. code = actions.join(' ');
  9151. }
  9152. const textarea = document.getElementById('modal-rf-rule');
  9153. if (textarea) textarea.value = code;
  9154. }
  9155. // -------------------------------------------------------------
  9156. // MODAL CRUD: RULES (/routing filter rule)
  9157. // -------------------------------------------------------------
  9158. function openAddRoutingFilterModal(defaultChain = '') {
  9159. const form = document.getElementById('routing-filter-form');
  9160. if (form) form.reset();
  9161. const idEl = document.getElementById('modal-rf-id');
  9162. if (idEl) idEl.value = '';
  9163. const titleEl = document.getElementById('modal-rf-title');
  9164. if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
  9165. const chainEl = document.getElementById('modal-rf-chain');
  9166. if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
  9167. const orderEl = document.getElementById('modal-rf-order');
  9168. if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
  9169. const ruleEl = document.getElementById('modal-rf-rule');
  9170. if (ruleEl) ruleEl.value = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  9171. const disEl = document.getElementById('modal-rf-disabled');
  9172. if (disEl) disEl.checked = false;
  9173. const modal = document.getElementById('modal-routing-filter');
  9174. if (modal) modal.classList.remove('hidden');
  9175. }
  9176. function openEditRoutingFilterModal(id) {
  9177. const r = (state.routingFilters || []).find(item => item.id === id);
  9178. if (!r) return;
  9179. const idEl = document.getElementById('modal-rf-id');
  9180. if (idEl) idEl.value = r.id;
  9181. const titleEl = document.getElementById('modal-rf-title');
  9182. if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
  9183. const chainEl = document.getElementById('modal-rf-chain');
  9184. if (chainEl) chainEl.value = r.chain || '';
  9185. const orderEl = document.getElementById('modal-rf-order');
  9186. if (orderEl) orderEl.value = r.rule_order || 10;
  9187. const ruleEl = document.getElementById('modal-rf-rule');
  9188. if (ruleEl) {
  9189. if (r.rule) {
  9190. ruleEl.value = r.rule;
  9191. } else {
  9192. let conds = [];
  9193. if (r.prefix) conds.push(`dst in ${r.prefix}`);
  9194. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${r.match_protocol}`);
  9195. let act = r.action || 'accept';
  9196. ruleEl.value = `if (${conds.length ? conds.join(' && ') : 'true'}) { ${act}; }`;
  9197. }
  9198. }
  9199. const comEl = document.getElementById('modal-rf-comment');
  9200. if (comEl) comEl.value = r.comment || '';
  9201. const disEl = document.getElementById('modal-rf-disabled');
  9202. if (disEl) disEl.checked = !!r.disabled;
  9203. const modal = document.getElementById('modal-routing-filter');
  9204. if (modal) modal.classList.remove('hidden');
  9205. }
  9206. function closeRoutingFilterModal() {
  9207. const modal = document.getElementById('modal-routing-filter');
  9208. if (modal) modal.classList.add('hidden');
  9209. }
  9210. async function submitRoutingFilter(e) {
  9211. if (e) e.preventDefault();
  9212. const payload = {
  9213. id: document.getElementById('modal-rf-id').value,
  9214. chain: document.getElementById('modal-rf-chain').value.trim(),
  9215. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  9216. rule: document.getElementById('modal-rf-rule').value.trim(),
  9217. comment: document.getElementById('modal-rf-comment').value.trim(),
  9218. disabled: document.getElementById('modal-rf-disabled').checked
  9219. };
  9220. try {
  9221. const res = await fetch(`${API_BASE}/routing/filters`, {
  9222. method: 'POST',
  9223. headers: { 'Content-Type': 'application/json' },
  9224. body: JSON.stringify(payload)
  9225. });
  9226. if (res.ok) {
  9227. closeRoutingFilterModal();
  9228. showToast('Success', 'Routing filter rule saved', 'success');
  9229. loadDynamicRouting();
  9230. } else {
  9231. const err = await res.json();
  9232. showToast('Error', err.error || 'Failed to save filter rule', 'error');
  9233. }
  9234. } catch (err) {
  9235. showToast('Error', err.message, 'error');
  9236. }
  9237. }
  9238. async function applyRoutingFilterForm() {
  9239. const payload = {
  9240. id: document.getElementById('modal-rf-id').value,
  9241. chain: document.getElementById('modal-rf-chain').value.trim(),
  9242. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  9243. rule: document.getElementById('modal-rf-rule').value.trim(),
  9244. comment: document.getElementById('modal-rf-comment').value.trim(),
  9245. disabled: document.getElementById('modal-rf-disabled').checked
  9246. };
  9247. try {
  9248. const res = await fetch(`${API_BASE}/routing/filters`, {
  9249. method: 'POST',
  9250. headers: { 'Content-Type': 'application/json' },
  9251. body: JSON.stringify(payload)
  9252. });
  9253. if (res.ok) {
  9254. const data = await res.json();
  9255. if (data.id) document.getElementById('modal-rf-id').value = data.id;
  9256. showToast('Applied', 'Routing filter configuration applied', 'success');
  9257. loadDynamicRouting();
  9258. } else {
  9259. const err = await res.json();
  9260. showToast('Error', err.error || 'Failed to apply filter rule', 'error');
  9261. }
  9262. } catch (err) {
  9263. showToast('Error', err.message, 'error');
  9264. }
  9265. }
  9266. async function moveRoutingFilterOrder(id, delta) {
  9267. const list = state.routingFilters || [];
  9268. const idx = list.findIndex(r => r.id === id);
  9269. if (idx < 0) return;
  9270. const targetIdx = idx + delta;
  9271. if (targetIdx < 0 || targetIdx >= list.length) return;
  9272. const currentOrder = list[idx].rule_order || 10;
  9273. const targetOrder = list[targetIdx].rule_order || 20;
  9274. list[idx].rule_order = targetOrder;
  9275. list[targetIdx].rule_order = currentOrder;
  9276. try {
  9277. await fetch(`${API_BASE}/routing/filters`, {
  9278. method: 'POST',
  9279. headers: { 'Content-Type': 'application/json' },
  9280. body: JSON.stringify(list[idx])
  9281. });
  9282. await fetch(`${API_BASE}/routing/filters`, {
  9283. method: 'POST',
  9284. headers: { 'Content-Type': 'application/json' },
  9285. body: JSON.stringify(list[targetIdx])
  9286. });
  9287. loadDynamicRouting();
  9288. } catch (e) {
  9289. console.error('Reorder error:', e);
  9290. }
  9291. }
  9292. async function deleteRoutingFilter(id) {
  9293. if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
  9294. try {
  9295. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9296. if (res.ok) {
  9297. showToast('Deleted', 'Routing filter rule removed', 'info');
  9298. loadDynamicRouting();
  9299. } else {
  9300. const err = await res.json();
  9301. showToast('Error', err.error || 'Failed to delete rule', 'error');
  9302. }
  9303. } catch (err) {
  9304. showToast('Error', err.message, 'error');
  9305. }
  9306. }
  9307. async function toggleRoutingFilterState(id, disabled) {
  9308. try {
  9309. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
  9310. method: 'POST',
  9311. headers: { 'Content-Type': 'application/json' },
  9312. body: JSON.stringify({ disabled })
  9313. });
  9314. if (res.ok) {
  9315. showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  9316. loadDynamicRouting();
  9317. } else {
  9318. const err = await res.json();
  9319. showToast('Error', err.error || 'Failed to toggle rule state', 'error');
  9320. }
  9321. } catch (err) {
  9322. showToast('Error', err.message, 'error');
  9323. }
  9324. }
  9325. // -------------------------------------------------------------
  9326. // MODAL CRUD: SELECT RULES (/routing filter select-rule)
  9327. // -------------------------------------------------------------
  9328. function openAddSelectRuleModal() {
  9329. document.getElementById('modal-rf-sr-id').value = '';
  9330. document.getElementById('modal-rf-sr-title').innerText = 'Add Routing Select Rule';
  9331. document.getElementById('modal-rf-sr-chain').value = state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-out';
  9332. document.getElementById('modal-rf-sr-order').value = ((state.routingSelectRules || []).length + 1) * 10;
  9333. document.getElementById('modal-rf-sr-rule').value = 'if (protocol bgp && dst in 10.0.0.0/8) { accept; }';
  9334. document.getElementById('modal-rf-sr-comment').value = '';
  9335. document.getElementById('modal-rf-sr-disabled').checked = false;
  9336. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  9337. }
  9338. function openEditSelectRuleModal(id) {
  9339. const r = (state.routingSelectRules || []).find(item => item.id === id);
  9340. if (!r) return;
  9341. document.getElementById('modal-rf-sr-id').value = r.id;
  9342. document.getElementById('modal-rf-sr-title').innerText = 'Edit Routing Select Rule';
  9343. document.getElementById('modal-rf-sr-chain').value = r.chain || '';
  9344. document.getElementById('modal-rf-sr-order').value = r.rule_order || 10;
  9345. document.getElementById('modal-rf-sr-rule').value = r.rule || '';
  9346. document.getElementById('modal-rf-sr-comment').value = r.comment || '';
  9347. document.getElementById('modal-rf-sr-disabled').checked = !!r.disabled;
  9348. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  9349. }
  9350. function closeSelectRuleModal() {
  9351. document.getElementById('modal-rf-select-rule').classList.add('hidden');
  9352. }
  9353. async function submitSelectRule(e) {
  9354. e.preventDefault();
  9355. const payload = {
  9356. id: document.getElementById('modal-rf-sr-id').value,
  9357. chain: document.getElementById('modal-rf-sr-chain').value.trim(),
  9358. rule_order: parseInt(document.getElementById('modal-rf-sr-order').value, 10) || 10,
  9359. rule: document.getElementById('modal-rf-sr-rule').value.trim(),
  9360. comment: document.getElementById('modal-rf-sr-comment').value.trim(),
  9361. disabled: document.getElementById('modal-rf-sr-disabled').checked
  9362. };
  9363. try {
  9364. const res = await fetch(`${API_BASE}/routing/filters/select-rules`, {
  9365. method: 'POST',
  9366. headers: { 'Content-Type': 'application/json' },
  9367. body: JSON.stringify(payload)
  9368. });
  9369. if (res.ok) {
  9370. closeSelectRuleModal();
  9371. showToast('Success', 'Select rule saved', 'success');
  9372. loadDynamicRouting();
  9373. } else {
  9374. const err = await res.json();
  9375. showToast('Error', err.error || 'Failed to save select rule', 'error');
  9376. }
  9377. } catch (err) {
  9378. showToast('Error', err.message, 'error');
  9379. }
  9380. }
  9381. async function deleteSelectRule(id) {
  9382. if (!confirm('Are you sure you want to delete this select rule?')) return;
  9383. try {
  9384. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9385. if (res.ok) {
  9386. showToast('Deleted', 'Select rule removed', 'info');
  9387. loadDynamicRouting();
  9388. } else {
  9389. const err = await res.json();
  9390. showToast('Error', err.error || 'Failed to delete select rule', 'error');
  9391. }
  9392. } catch (err) {
  9393. showToast('Error', err.message, 'error');
  9394. }
  9395. }
  9396. async function toggleSelectRuleState(id, disabled) {
  9397. try {
  9398. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}/state`, {
  9399. method: 'POST',
  9400. headers: { 'Content-Type': 'application/json' },
  9401. body: JSON.stringify({ disabled })
  9402. });
  9403. if (res.ok) {
  9404. showToast('Status Updated', `Select rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  9405. loadDynamicRouting();
  9406. } else {
  9407. const err = await res.json();
  9408. showToast('Error', err.error || 'Failed to update select rule state', 'error');
  9409. }
  9410. } catch (err) {
  9411. showToast('Error', err.message, 'error');
  9412. }
  9413. }
  9414. // -------------------------------------------------------------
  9415. // MODAL CRUD: COMMUNITY LISTS (/routing filter community-list)
  9416. // -------------------------------------------------------------
  9417. function openAddCommunityListModal() {
  9418. document.getElementById('modal-rf-cl-id').value = '';
  9419. document.getElementById('modal-rf-cl-title').innerText = 'Add BGP Community List';
  9420. document.getElementById('modal-rf-cl-name').value = '';
  9421. document.getElementById('modal-rf-cl-communities').value = '';
  9422. document.getElementById('modal-rf-cl-regexp').value = '';
  9423. document.getElementById('modal-rf-cl-comment').value = '';
  9424. document.getElementById('modal-rf-cl-disabled').checked = false;
  9425. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  9426. }
  9427. function openEditCommunityListModal(id) {
  9428. const cl = (state.routingCommunityLists || []).find(item => item.id === id);
  9429. if (!cl) return;
  9430. document.getElementById('modal-rf-cl-id').value = cl.id;
  9431. document.getElementById('modal-rf-cl-title').innerText = 'Edit BGP Community List';
  9432. document.getElementById('modal-rf-cl-name').value = cl.name || '';
  9433. document.getElementById('modal-rf-cl-communities').value = (cl.communities || []).join(', ');
  9434. document.getElementById('modal-rf-cl-regexp').value = cl.regexp || '';
  9435. document.getElementById('modal-rf-cl-comment').value = cl.comment || '';
  9436. document.getElementById('modal-rf-cl-disabled').checked = !!cl.disabled;
  9437. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  9438. }
  9439. function closeCommunityListModal() {
  9440. document.getElementById('modal-rf-community-list').classList.add('hidden');
  9441. }
  9442. async function submitCommunityList(e) {
  9443. e.preventDefault();
  9444. const rawComms = document.getElementById('modal-rf-cl-communities').value;
  9445. const comms = rawComms.split(',').map(c => c.trim()).filter(Boolean);
  9446. const payload = {
  9447. id: document.getElementById('modal-rf-cl-id').value,
  9448. name: document.getElementById('modal-rf-cl-name').value.trim(),
  9449. communities: comms,
  9450. regexp: document.getElementById('modal-rf-cl-regexp').value.trim(),
  9451. comment: document.getElementById('modal-rf-cl-comment').value.trim(),
  9452. disabled: document.getElementById('modal-rf-cl-disabled').checked
  9453. };
  9454. try {
  9455. const res = await fetch(`${API_BASE}/routing/filters/community-lists`, {
  9456. method: 'POST',
  9457. headers: { 'Content-Type': 'application/json' },
  9458. body: JSON.stringify(payload)
  9459. });
  9460. if (res.ok) {
  9461. closeCommunityListModal();
  9462. showToast('Success', 'Community list saved', 'success');
  9463. loadDynamicRouting();
  9464. } else {
  9465. const err = await res.json();
  9466. showToast('Error', err.error || 'Failed to save community list', 'error');
  9467. }
  9468. } catch (err) {
  9469. showToast('Error', err.message, 'error');
  9470. }
  9471. }
  9472. async function deleteCommunityList(id) {
  9473. if (!confirm('Are you sure you want to delete this community list?')) return;
  9474. try {
  9475. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9476. if (res.ok) {
  9477. showToast('Deleted', 'Community list removed', 'info');
  9478. loadDynamicRouting();
  9479. } else {
  9480. const err = await res.json();
  9481. showToast('Error', err.error || 'Failed to delete community list', 'error');
  9482. }
  9483. } catch (err) {
  9484. showToast('Error', err.message, 'error');
  9485. }
  9486. }
  9487. async function toggleCommunityListState(id, disabled) {
  9488. try {
  9489. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}/state`, {
  9490. method: 'POST',
  9491. headers: { 'Content-Type': 'application/json' },
  9492. body: JSON.stringify({ disabled })
  9493. });
  9494. if (res.ok) {
  9495. showToast('Status Updated', `Community list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  9496. loadDynamicRouting();
  9497. } else {
  9498. const err = await res.json();
  9499. showToast('Error', err.error || 'Failed to update community list state', 'error');
  9500. }
  9501. } catch (err) {
  9502. showToast('Error', err.message, 'error');
  9503. }
  9504. }
  9505. // -------------------------------------------------------------
  9506. // MODAL CRUD: AS LISTS (/routing filter num-list)
  9507. // -------------------------------------------------------------
  9508. function openAddASListModal() {
  9509. document.getElementById('modal-rf-al-id').value = '';
  9510. document.getElementById('modal-rf-al-title').innerText = 'Add AS Number List';
  9511. document.getElementById('modal-rf-al-name').value = '';
  9512. document.getElementById('modal-rf-al-range').value = '';
  9513. document.getElementById('modal-rf-al-comment').value = '';
  9514. document.getElementById('modal-rf-al-disabled').checked = false;
  9515. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  9516. }
  9517. function openEditASListModal(id) {
  9518. const al = (state.routingASLists || []).find(item => item.id === id);
  9519. if (!al) return;
  9520. document.getElementById('modal-rf-al-id').value = al.id;
  9521. document.getElementById('modal-rf-al-title').innerText = 'Edit AS Number List';
  9522. document.getElementById('modal-rf-al-name').value = al.name || '';
  9523. document.getElementById('modal-rf-al-range').value = al.range || '';
  9524. document.getElementById('modal-rf-al-comment').value = al.comment || '';
  9525. document.getElementById('modal-rf-al-disabled').checked = !!al.disabled;
  9526. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  9527. }
  9528. function closeASListModal() {
  9529. document.getElementById('modal-rf-as-list').classList.add('hidden');
  9530. }
  9531. async function submitASList(e) {
  9532. e.preventDefault();
  9533. const payload = {
  9534. id: document.getElementById('modal-rf-al-id').value,
  9535. name: document.getElementById('modal-rf-al-name').value.trim(),
  9536. range: document.getElementById('modal-rf-al-range').value.trim(),
  9537. comment: document.getElementById('modal-rf-al-comment').value.trim(),
  9538. disabled: document.getElementById('modal-rf-al-disabled').checked
  9539. };
  9540. try {
  9541. const res = await fetch(`${API_BASE}/routing/filters/as-lists`, {
  9542. method: 'POST',
  9543. headers: { 'Content-Type': 'application/json' },
  9544. body: JSON.stringify(payload)
  9545. });
  9546. if (res.ok) {
  9547. closeASListModal();
  9548. showToast('Success', 'AS number list saved', 'success');
  9549. loadDynamicRouting();
  9550. } else {
  9551. const err = await res.json();
  9552. showToast('Error', err.error || 'Failed to save AS list', 'error');
  9553. }
  9554. } catch (err) {
  9555. showToast('Error', err.message, 'error');
  9556. }
  9557. }
  9558. async function deleteASList(id) {
  9559. if (!confirm('Are you sure you want to delete this AS list?')) return;
  9560. try {
  9561. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9562. if (res.ok) {
  9563. showToast('Deleted', 'AS list removed', 'info');
  9564. loadDynamicRouting();
  9565. } else {
  9566. const err = await res.json();
  9567. showToast('Error', err.error || 'Failed to delete AS list', 'error');
  9568. }
  9569. } catch (err) {
  9570. showToast('Error', err.message, 'error');
  9571. }
  9572. }
  9573. async function toggleASListState(id, disabled) {
  9574. try {
  9575. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}/state`, {
  9576. method: 'POST',
  9577. headers: { 'Content-Type': 'application/json' },
  9578. body: JSON.stringify({ disabled })
  9579. });
  9580. if (res.ok) {
  9581. showToast('Status Updated', `AS list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  9582. loadDynamicRouting();
  9583. } else {
  9584. const err = await res.json();
  9585. showToast('Error', err.error || 'Failed to update AS list state', 'error');
  9586. }
  9587. } catch (err) {
  9588. showToast('Error', err.message, 'error');
  9589. }
  9590. }
  9591. // ==========================================
  9592. // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
  9593. // ==========================================
  9594. function loadToolsView() {
  9595. populateToolsInterfaces();
  9596. switchToolsSubTab(state.activeToolsSubTab || 'ping');
  9597. }
  9598. function populateToolsInterfaces() {
  9599. const pingSel = document.getElementById('tools-ping-iface');
  9600. const traceSel = document.getElementById('tools-tr-iface');
  9601. let opts = '<option value="">Auto (Default Route)</option>';
  9602. if (Array.isArray(state.interfaces)) {
  9603. state.interfaces.forEach(iface => {
  9604. if (iface.name) {
  9605. opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
  9606. }
  9607. });
  9608. }
  9609. if (pingSel) {
  9610. const cur = pingSel.value;
  9611. pingSel.innerHTML = opts;
  9612. if (cur) pingSel.value = cur;
  9613. }
  9614. if (traceSel) {
  9615. const cur = traceSel.value;
  9616. traceSel.innerHTML = opts;
  9617. if (cur) traceSel.value = cur;
  9618. }
  9619. }
  9620. function switchToolsSubTab(subTab) {
  9621. state.activeToolsSubTab = subTab;
  9622. const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
  9623. tabs.forEach(t => {
  9624. const btn = document.getElementById(`tools-subtab-btn-${t}`);
  9625. const view = document.getElementById(`tools-view-${t}`);
  9626. if (btn) {
  9627. if (t === subTab) {
  9628. 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';
  9629. } else {
  9630. 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';
  9631. }
  9632. }
  9633. if (view) {
  9634. if (t === subTab) {
  9635. view.classList.remove('hidden');
  9636. } else {
  9637. view.classList.add('hidden');
  9638. }
  9639. }
  9640. });
  9641. }
  9642. function setPortPreset(port) {
  9643. const input = document.getElementById('tools-port-num');
  9644. if (input) input.value = port;
  9645. }
  9646. let pingAbortController = null;
  9647. let tracerouteAbortController = null;
  9648. function clearPingTable() {
  9649. const tbody = document.getElementById('tools-ping-tbody');
  9650. if (tbody) tbody.innerHTML = '';
  9651. const rawEl = document.getElementById('tools-ping-raw');
  9652. if (rawEl) rawEl.innerText = '';
  9653. const sentEl = document.getElementById('tools-ping-stat-sent');
  9654. if (sentEl) sentEl.innerText = '0';
  9655. const recvEl = document.getElementById('tools-ping-stat-recv');
  9656. if (recvEl) recvEl.innerText = '0';
  9657. const lossEl = document.getElementById('tools-ping-stat-loss');
  9658. if (lossEl) lossEl.innerText = '0%';
  9659. const avgEl = document.getElementById('tools-ping-stat-avg');
  9660. if (avgEl) avgEl.innerText = '0 ms';
  9661. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  9662. if (minMaxEl) minMaxEl.innerText = '-';
  9663. const badge = document.getElementById('tools-ping-status-badge');
  9664. if (badge) {
  9665. badge.className = '';
  9666. badge.innerText = '';
  9667. }
  9668. }
  9669. function clearTracerouteTable() {
  9670. const tbody = document.getElementById('tools-tr-tbody');
  9671. if (tbody) tbody.innerHTML = '';
  9672. const rawEl = document.getElementById('tools-tr-raw');
  9673. if (rawEl) rawEl.innerText = '';
  9674. const statHops = document.getElementById('tools-tr-hops-count');
  9675. if (statHops) statHops.innerText = '0 Hops';
  9676. }
  9677. function resetPingButton() {
  9678. const btn = document.getElementById('tools-ping-btn');
  9679. const btnText = document.getElementById('tools-ping-btn-text');
  9680. const spinner = document.getElementById('tools-ping-spinner');
  9681. if (btn) {
  9682. btn.disabled = false;
  9683. 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';
  9684. }
  9685. if (btnText) btnText.innerText = 'Start Ping';
  9686. if (spinner) spinner.classList.add('hidden');
  9687. }
  9688. function setPingRunningButton() {
  9689. const btn = document.getElementById('tools-ping-btn');
  9690. const btnText = document.getElementById('tools-ping-btn-text');
  9691. const spinner = document.getElementById('tools-ping-spinner');
  9692. if (btn) {
  9693. btn.disabled = false;
  9694. 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';
  9695. }
  9696. if (btnText) btnText.innerText = 'Stop Ping';
  9697. if (spinner) spinner.classList.remove('hidden');
  9698. }
  9699. function resetTracerouteButton() {
  9700. const btn = document.getElementById('tools-tr-btn');
  9701. const btnText = document.getElementById('tools-tr-btn-text');
  9702. const spinner = document.getElementById('tools-tr-spinner');
  9703. if (btn) {
  9704. btn.disabled = false;
  9705. 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';
  9706. }
  9707. if (btnText) btnText.innerText = 'Start Traceroute';
  9708. if (spinner) spinner.classList.add('hidden');
  9709. }
  9710. function setTracerouteRunningButton() {
  9711. const btn = document.getElementById('tools-tr-btn');
  9712. const btnText = document.getElementById('tools-tr-btn-text');
  9713. const spinner = document.getElementById('tools-tr-spinner');
  9714. if (btn) {
  9715. btn.disabled = false;
  9716. 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';
  9717. }
  9718. if (btnText) btnText.innerText = 'Stop Traceroute';
  9719. if (spinner) spinner.classList.remove('hidden');
  9720. }
  9721. async function executePing(e) {
  9722. if (e) e.preventDefault();
  9723. // If already running, clicking the button stops the stream!
  9724. if (pingAbortController) {
  9725. pingAbortController.abort();
  9726. pingAbortController = null;
  9727. resetPingButton();
  9728. showToast('Ping Stopped', 'Live ping stopped by user', 'info');
  9729. return;
  9730. }
  9731. const target = document.getElementById('tools-ping-target')?.value?.trim();
  9732. const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
  9733. const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
  9734. const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '3', 10);
  9735. const iface = document.getElementById('tools-ping-iface')?.value || '';
  9736. const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
  9737. if (!target) {
  9738. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  9739. return;
  9740. }
  9741. clearPingTable();
  9742. const resCard = document.getElementById('tools-ping-results');
  9743. if (resCard) resCard.classList.remove('hidden');
  9744. pingAbortController = new AbortController();
  9745. setPingRunningButton();
  9746. try {
  9747. const res = await fetch(`${API_BASE}/tools/ping/stream`, {
  9748. method: 'POST',
  9749. headers: { 'Content-Type': 'application/json' },
  9750. body: JSON.stringify({
  9751. target,
  9752. count,
  9753. size,
  9754. timeout,
  9755. interface: iface,
  9756. dont_frag: dontFrag
  9757. }),
  9758. signal: pingAbortController.signal
  9759. });
  9760. if (!res.ok) {
  9761. const errText = await res.text();
  9762. showToast('Ping Error', errText || 'Failed to start live ping', 'error');
  9763. resetPingButton();
  9764. pingAbortController = null;
  9765. return;
  9766. }
  9767. const reader = res.body.getReader();
  9768. const decoder = new TextDecoder('utf-8');
  9769. let buffer = '';
  9770. while (true) {
  9771. const { done, value } = await reader.read();
  9772. if (done) break;
  9773. buffer += decoder.decode(value, { stream: true });
  9774. const blocks = buffer.split('\n\n');
  9775. buffer = blocks.pop() || '';
  9776. for (const block of blocks) {
  9777. const trimmed = block.trim();
  9778. if (!trimmed) continue;
  9779. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  9780. try {
  9781. const evt = JSON.parse(line);
  9782. handleLivePingEvent(evt);
  9783. } catch (parseErr) {
  9784. console.warn('Ping SSE parse error:', parseErr, line);
  9785. }
  9786. }
  9787. }
  9788. } catch (err) {
  9789. if (err.name === 'AbortError') {
  9790. // User aborted normally
  9791. } else {
  9792. showToast('Ping Error', err.message, 'error');
  9793. }
  9794. } finally {
  9795. pingAbortController = null;
  9796. resetPingButton();
  9797. }
  9798. }
  9799. function handleLivePingEvent(evt) {
  9800. const sentEl = document.getElementById('tools-ping-stat-sent');
  9801. const recvEl = document.getElementById('tools-ping-stat-recv');
  9802. const lossEl = document.getElementById('tools-ping-stat-loss');
  9803. const avgEl = document.getElementById('tools-ping-stat-avg');
  9804. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  9805. const badge = document.getElementById('tools-ping-status-badge');
  9806. const tbody = document.getElementById('tools-ping-tbody');
  9807. const rawEl = document.getElementById('tools-ping-raw');
  9808. if (evt.raw && rawEl) {
  9809. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  9810. rawEl.scrollTop = rawEl.scrollHeight;
  9811. }
  9812. if (evt.type === 'reply') {
  9813. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  9814. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  9815. if (lossEl && evt.packet_loss_pct !== undefined) {
  9816. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  9817. lossEl.className = evt.packet_loss_pct === 0
  9818. ? 'text-base font-bold font-mono text-emerald-400 mt-1'
  9819. : (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');
  9820. }
  9821. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  9822. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  9823. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  9824. }
  9825. if (badge) {
  9826. if (evt.packet_loss_pct === 0) {
  9827. 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';
  9828. badge.innerText = '100% OK';
  9829. } else {
  9830. 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';
  9831. badge.innerText = `${evt.packet_loss_pct.toFixed(0)}% LOSS`;
  9832. }
  9833. }
  9834. if (tbody) {
  9835. const tr = document.createElement('tr');
  9836. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  9837. tr.innerHTML = `
  9838. <td class="py-2 px-3 text-slate-300">#${evt.seq}</td>
  9839. <td class="py-2 px-3 font-semibold text-white">${escapeHtml(evt.from)}</td>
  9840. <td class="py-2 px-3 text-slate-400">${evt.bytes} bytes</td>
  9841. <td class="py-2 px-3 text-slate-300">${evt.ttl}</td>
  9842. <td class="py-2 px-3 font-bold text-amber-300">${evt.time_ms.toFixed(2)} ms</td>
  9843. <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>
  9844. `;
  9845. tbody.appendChild(tr);
  9846. }
  9847. } else if (evt.type === 'timeout') {
  9848. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  9849. if (lossEl && evt.packet_loss_pct !== undefined) {
  9850. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  9851. 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';
  9852. }
  9853. if (badge) {
  9854. 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';
  9855. badge.innerText = `${evt.packet_loss_pct?.toFixed(0) || 100}% LOSS`;
  9856. }
  9857. if (tbody) {
  9858. const tr = document.createElement('tr');
  9859. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs opacity-75';
  9860. tr.innerHTML = `
  9861. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  9862. <td class="py-2 px-3 font-semibold text-slate-500 italic">Request timed out</td>
  9863. <td class="py-2 px-3 text-slate-600">--</td>
  9864. <td class="py-2 px-3 text-slate-600">--</td>
  9865. <td class="py-2 px-3 font-bold text-slate-500">* * *</td>
  9866. <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>
  9867. `;
  9868. tbody.appendChild(tr);
  9869. }
  9870. } else if (evt.type === 'unreach') {
  9871. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  9872. if (lossEl && evt.packet_loss_pct !== undefined) {
  9873. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  9874. lossEl.className = 'text-base font-bold font-mono text-rose-400 mt-1';
  9875. }
  9876. if (badge) {
  9877. 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';
  9878. badge.innerText = 'UNREACHABLE';
  9879. }
  9880. if (tbody) {
  9881. const tr = document.createElement('tr');
  9882. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  9883. tr.innerHTML = `
  9884. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  9885. <td class="py-2 px-3 font-semibold text-rose-400">${escapeHtml(evt.from || 'Gateway')}</td>
  9886. <td class="py-2 px-3 text-slate-600">--</td>
  9887. <td class="py-2 px-3 text-slate-600">--</td>
  9888. <td class="py-2 px-3 font-bold text-rose-400 text-xs">${escapeHtml(evt.message || 'Unreachable')}</td>
  9889. <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>
  9890. `;
  9891. tbody.appendChild(tr);
  9892. }
  9893. } else if (evt.type === 'stats') {
  9894. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  9895. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  9896. if (lossEl && evt.packet_loss_pct !== undefined) lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  9897. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  9898. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  9899. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  9900. }
  9901. } else if (evt.type === 'done') {
  9902. 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');
  9903. }
  9904. }
  9905. async function executeTraceroute(e) {
  9906. if (e) e.preventDefault();
  9907. if (tracerouteAbortController) {
  9908. tracerouteAbortController.abort();
  9909. tracerouteAbortController = null;
  9910. resetTracerouteButton();
  9911. showToast('Traceroute Stopped', 'Traceroute stopped by user', 'info');
  9912. return;
  9913. }
  9914. const target = document.getElementById('tools-tr-target')?.value?.trim();
  9915. const maxHops = parseInt(document.getElementById('tools-tr-maxhops')?.value || '15', 10);
  9916. const protocol = document.getElementById('tools-tr-proto')?.value || 'icmp';
  9917. const iface = document.getElementById('tools-tr-iface')?.value || '';
  9918. const resolve = document.getElementById('tools-tr-resolve')?.checked || false;
  9919. if (!target) {
  9920. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  9921. return;
  9922. }
  9923. clearTracerouteTable();
  9924. const resCard = document.getElementById('tools-tr-results');
  9925. if (resCard) resCard.classList.remove('hidden');
  9926. tracerouteAbortController = new AbortController();
  9927. setTracerouteRunningButton();
  9928. try {
  9929. const res = await fetch(`${API_BASE}/tools/traceroute/stream`, {
  9930. method: 'POST',
  9931. headers: { 'Content-Type': 'application/json' },
  9932. body: JSON.stringify({
  9933. target,
  9934. max_hops: maxHops,
  9935. protocol,
  9936. interface: iface,
  9937. resolve
  9938. }),
  9939. signal: tracerouteAbortController.signal
  9940. });
  9941. if (!res.ok) {
  9942. const errText = await res.text();
  9943. showToast('Traceroute Error', errText || 'Failed to start traceroute', 'error');
  9944. resetTracerouteButton();
  9945. tracerouteAbortController = null;
  9946. return;
  9947. }
  9948. const reader = res.body.getReader();
  9949. const decoder = new TextDecoder('utf-8');
  9950. let buffer = '';
  9951. while (true) {
  9952. const { done, value } = await reader.read();
  9953. if (done) break;
  9954. buffer += decoder.decode(value, { stream: true });
  9955. const blocks = buffer.split('\n\n');
  9956. buffer = blocks.pop() || '';
  9957. for (const block of blocks) {
  9958. const trimmed = block.trim();
  9959. if (!trimmed) continue;
  9960. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  9961. try {
  9962. const evt = JSON.parse(line);
  9963. handleLiveTracerouteEvent(evt);
  9964. } catch (parseErr) {
  9965. console.warn('Traceroute SSE parse error:', parseErr, line);
  9966. }
  9967. }
  9968. }
  9969. } catch (err) {
  9970. if (err.name === 'AbortError') {
  9971. // User aborted normally
  9972. } else {
  9973. showToast('Traceroute Error', err.message, 'error');
  9974. }
  9975. } finally {
  9976. tracerouteAbortController = null;
  9977. resetTracerouteButton();
  9978. }
  9979. }
  9980. function handleLiveTracerouteEvent(evt) {
  9981. const statHops = document.getElementById('tools-tr-hops-count');
  9982. const tbody = document.getElementById('tools-tr-tbody');
  9983. const rawEl = document.getElementById('tools-tr-raw');
  9984. if (evt.raw && rawEl) {
  9985. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  9986. rawEl.scrollTop = rawEl.scrollHeight;
  9987. }
  9988. if (evt.hops_count !== undefined && statHops) {
  9989. statHops.innerText = `${evt.hops_count} Hops`;
  9990. }
  9991. if (evt.type === 'hop' && evt.hop && tbody) {
  9992. const h = evt.hop;
  9993. const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
  9994. const rtt1 = Array.isArray(h.times_ms) && h.times_ms[0] ? `${h.times_ms[0]} ms` : (isTimeout ? '*' : '--');
  9995. const rtt2 = Array.isArray(h.times_ms) && h.times_ms[1] ? `${h.times_ms[1]} ms` : (isTimeout ? '*' : '--');
  9996. const displayHost = h.host && h.host !== h.ip ? `${escapeHtml(h.host)} (${escapeHtml(h.ip || '')})` : escapeHtml(h.ip || (isTimeout ? 'Request timed out' : '--'));
  9997. const tr = document.createElement('tr');
  9998. tr.className = `hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}`;
  9999. tr.innerHTML = `
  10000. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  10001. <td class="py-2.5 px-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${displayHost}</td>
  10002. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt1)}</td>
  10003. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt2)}</td>
  10004. <td class="py-2.5 px-3 text-right">
  10005. ${isTimeout
  10006. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
  10007. : '<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>'}
  10008. </td>
  10009. `;
  10010. tbody.appendChild(tr);
  10011. } else if (evt.type === 'done') {
  10012. showToast('Traceroute Finished', `Traced ${evt.hops_count || 0} hops`, 'info');
  10013. }
  10014. }
  10015. async function executeMTR(e) {
  10016. if (e) e.preventDefault();
  10017. const target = document.getElementById('tools-mtr-target')?.value?.trim();
  10018. const cycles = parseInt(document.getElementById('tools-mtr-count')?.value || '3', 10);
  10019. if (!target) {
  10020. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  10021. return;
  10022. }
  10023. const btn = document.getElementById('tools-mtr-btn');
  10024. const spinner = document.getElementById('tools-mtr-spinner');
  10025. if (btn) btn.disabled = true;
  10026. if (spinner) spinner.classList.remove('hidden');
  10027. try {
  10028. const res = await fetch(`${API_BASE}/tools/mtr`, {
  10029. method: 'POST',
  10030. headers: { 'Content-Type': 'application/json' },
  10031. body: JSON.stringify({ target, count: cycles })
  10032. });
  10033. const data = await res.json();
  10034. if (!res.ok) {
  10035. showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
  10036. return;
  10037. }
  10038. const resCard = document.getElementById('tools-mtr-results');
  10039. if (resCard) resCard.classList.remove('hidden');
  10040. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  10041. const statHops = document.getElementById('tools-mtr-hops-count');
  10042. if (statHops) statHops.innerText = `${hopsCount} Hops`;
  10043. const tbody = document.getElementById('tools-mtr-tbody');
  10044. if (tbody) {
  10045. if (hopsCount > 0) {
  10046. tbody.innerHTML = data.hops.map(h => {
  10047. 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');
  10048. return `
  10049. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  10050. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  10051. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
  10052. <td class="py-2.5 px-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
  10053. <td class="py-2.5 px-3 text-slate-300">${h.sent}</td>
  10054. <td class="py-2.5 px-3 text-slate-300">${h.last_ms.toFixed(1)}</td>
  10055. <td class="py-2.5 px-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)}</td>
  10056. <td class="py-2.5 px-3 text-emerald-400">${h.best_ms.toFixed(1)}</td>
  10057. <td class="py-2.5 px-3 text-rose-400">${h.wrst_ms.toFixed(1)}</td>
  10058. <td class="py-2.5 px-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
  10059. </tr>
  10060. `;
  10061. }).join('');
  10062. } else {
  10063. tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
  10064. }
  10065. }
  10066. const rawEl = document.getElementById('tools-mtr-raw');
  10067. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  10068. showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
  10069. } catch (err) {
  10070. showToast('MTR Error', err.message, 'error');
  10071. } finally {
  10072. if (btn) btn.disabled = false;
  10073. if (spinner) spinner.classList.add('hidden');
  10074. }
  10075. }
  10076. async function executeDNS(e) {
  10077. if (e) e.preventDefault();
  10078. const domain = document.getElementById('tools-dns-domain')?.value?.trim();
  10079. const type = document.getElementById('tools-dns-type')?.value || 'A';
  10080. const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
  10081. if (!domain) {
  10082. showToast('Input Required', 'Please enter a hostname or domain', 'warning');
  10083. return;
  10084. }
  10085. const btn = document.getElementById('tools-dns-btn');
  10086. const spinner = document.getElementById('tools-dns-spinner');
  10087. if (btn) btn.disabled = true;
  10088. if (spinner) spinner.classList.remove('hidden');
  10089. try {
  10090. const res = await fetch(`${API_BASE}/tools/dns`, {
  10091. method: 'POST',
  10092. headers: { 'Content-Type': 'application/json' },
  10093. body: JSON.stringify({ domain, type, server })
  10094. });
  10095. const data = await res.json();
  10096. if (!res.ok) {
  10097. showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
  10098. return;
  10099. }
  10100. const resCard = document.getElementById('tools-dns-results');
  10101. if (resCard) resCard.classList.remove('hidden');
  10102. const metaEl = document.getElementById('tools-dns-meta');
  10103. if (metaEl) metaEl.innerText = `Resolved in ${data.query_time_ms ?? 0} ms via ${escapeHtml(data.server || 'System DNS')}`;
  10104. const tbody = document.getElementById('tools-dns-tbody');
  10105. if (tbody) {
  10106. if (Array.isArray(data.records) && data.records.length > 0) {
  10107. tbody.innerHTML = data.records.map(r => `
  10108. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  10109. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.name)}</td>
  10110. <td class="py-2.5 px-3 text-slate-400">${r.ttl}s</td>
  10111. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.class || 'IN')}</td>
  10112. <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>
  10113. <td class="py-2.5 px-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
  10114. </tr>
  10115. `).join('');
  10116. } else {
  10117. 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>`;
  10118. }
  10119. }
  10120. const rawEl = document.getElementById('tools-dns-raw');
  10121. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  10122. showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
  10123. } catch (err) {
  10124. showToast('DNS Error', err.message, 'error');
  10125. } finally {
  10126. if (btn) btn.disabled = false;
  10127. if (spinner) spinner.classList.add('hidden');
  10128. }
  10129. }
  10130. async function executePortProbe(e) {
  10131. if (e) e.preventDefault();
  10132. const target = document.getElementById('tools-port-target')?.value?.trim();
  10133. const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
  10134. const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
  10135. if (!target || !port) {
  10136. showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
  10137. return;
  10138. }
  10139. const btn = document.getElementById('tools-port-btn');
  10140. const spinner = document.getElementById('tools-port-spinner');
  10141. if (btn) btn.disabled = true;
  10142. if (spinner) spinner.classList.remove('hidden');
  10143. try {
  10144. const res = await fetch(`${API_BASE}/tools/port-probe`, {
  10145. method: 'POST',
  10146. headers: { 'Content-Type': 'application/json' },
  10147. body: JSON.stringify({ target, port, timeout })
  10148. });
  10149. const data = await res.json();
  10150. if (!res.ok) {
  10151. showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
  10152. return;
  10153. }
  10154. const resCard = document.getElementById('tools-port-results');
  10155. if (resCard) resCard.classList.remove('hidden');
  10156. const banner = document.getElementById('tools-port-banner');
  10157. const icon = document.getElementById('tools-port-icon');
  10158. const title = document.getElementById('tools-port-title');
  10159. const sub = document.getElementById('tools-port-sub');
  10160. const latency = document.getElementById('tools-port-latency');
  10161. if (data.open) {
  10162. if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
  10163. if (icon) {
  10164. 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';
  10165. icon.innerText = '✓';
  10166. }
  10167. if (title) {
  10168. title.className = 'text-sm font-bold text-emerald-300';
  10169. title.innerText = `PORT ${port} OPEN / LISTENING`;
  10170. }
  10171. if (sub) {
  10172. sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
  10173. sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
  10174. }
  10175. if (latency) {
  10176. latency.className = 'text-base font-bold font-mono text-emerald-300';
  10177. latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
  10178. }
  10179. } else {
  10180. if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-800/50 flex items-center justify-between';
  10181. if (icon) {
  10182. 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';
  10183. icon.innerText = '✕';
  10184. }
  10185. if (title) {
  10186. title.className = 'text-sm font-bold text-rose-300';
  10187. title.innerText = `PORT ${port} CLOSED / FILTERED`;
  10188. }
  10189. if (sub) {
  10190. sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
  10191. sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
  10192. }
  10193. if (latency) {
  10194. latency.className = 'text-base font-bold font-mono text-slate-500';
  10195. latency.innerText = '--';
  10196. }
  10197. }
  10198. const rawEl = document.getElementById('tools-port-raw');
  10199. 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'}`);
  10200. showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
  10201. } catch (err) {
  10202. showToast('Probe Error', err.message, 'error');
  10203. } finally {
  10204. if (btn) btn.disabled = false;
  10205. if (spinner) spinner.classList.add('hidden');
  10206. }
  10207. }
  10208. // ==========================================
  10209. // DHCP CLIENT (/ip dhcp-client) CONTROLLER
  10210. // ==========================================
  10211. async function loadDHCPClients(showToastMsg = false) {
  10212. try {
  10213. const [clientsRes, sumRes] = await Promise.all([
  10214. fetch(`${API_BASE}/dhcp/clients`),
  10215. fetch(`${API_BASE}/dhcp/clients/summary`)
  10216. ]);
  10217. if (clientsRes.ok) {
  10218. state.dhcpClients = await clientsRes.json();
  10219. }
  10220. if (sumRes.ok) {
  10221. state.dhcpSummary = await sumRes.json();
  10222. }
  10223. renderDHCPClients();
  10224. updateDHCPSummaryCards();
  10225. const bDhcp = document.getElementById('badge-dhcp-client-count');
  10226. if (bDhcp && state.dhcpSummary) {
  10227. bDhcp.innerText = state.dhcpSummary.total_clients || 0;
  10228. }
  10229. if (showToastMsg) {
  10230. showToast('Refreshed', 'DHCP Client telemetry updated', 'info');
  10231. }
  10232. } catch (err) {
  10233. console.error('Failed to load DHCP clients:', err);
  10234. if (showToastMsg) {
  10235. showToast('Notice', 'Unable to fetch DHCP client status', 'warning');
  10236. }
  10237. }
  10238. }
  10239. function updateDHCPSummaryCards() {
  10240. const sum = state.dhcpSummary || {
  10241. total_clients: (state.dhcpClients || []).length,
  10242. bound_clients: (state.dhcpClients || []).filter(c => c.status === 'bound').length,
  10243. searching_clients: (state.dhcpClients || []).filter(c => c.status === 'searching').length,
  10244. disabled_clients: (state.dhcpClients || []).filter(c => !c.enabled).length
  10245. };
  10246. const totalEl = document.getElementById('dhcp-stat-total');
  10247. const boundEl = document.getElementById('dhcp-stat-bound');
  10248. const searchEl = document.getElementById('dhcp-stat-searching');
  10249. const disEl = document.getElementById('dhcp-stat-disabled');
  10250. if (totalEl) totalEl.innerText = sum.total_clients ?? 0;
  10251. if (boundEl) boundEl.innerText = sum.bound_clients ?? 0;
  10252. if (searchEl) searchEl.innerText = sum.searching_clients ?? 0;
  10253. if (disEl) disEl.innerText = sum.disabled_clients ?? 0;
  10254. }
  10255. function renderDHCPClients() {
  10256. const tbody = document.getElementById('dhcp-clients-tbody');
  10257. const emptyState = document.getElementById('dhcp-clients-empty');
  10258. if (!tbody) return;
  10259. const clients = Array.isArray(state.dhcpClients) ? state.dhcpClients : [];
  10260. if (clients.length === 0) {
  10261. tbody.innerHTML = '';
  10262. if (emptyState) emptyState.classList.remove('hidden');
  10263. return;
  10264. }
  10265. if (emptyState) emptyState.classList.add('hidden');
  10266. tbody.innerHTML = clients.map(c => {
  10267. let statusBadge = '';
  10268. if (!c.enabled) {
  10269. 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>';
  10270. } else if (c.status === 'bound') {
  10271. 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>';
  10272. } else if (c.status === 'searching') {
  10273. 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>';
  10274. } else if (c.status === 'stopped') {
  10275. 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>';
  10276. } else {
  10277. 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>`;
  10278. }
  10279. 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>';
  10280. const gwDisplay = c.gateway ? `<span class="text-slate-300">${escapeHtml(c.gateway)}</span>` : '<span class="text-slate-600">--</span>';
  10281. const srvDisplay = c.dhcp_server ? `<span class="text-slate-300">${escapeHtml(c.dhcp_server)}</span>` : '<span class="text-slate-600">--</span>';
  10282. 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>';
  10283. const expDisplay = c.expires_in ? `<span class="text-purple-300">${escapeHtml(c.expires_in)}</span>` : '<span class="text-slate-600">--</span>';
  10284. // Option flags
  10285. const flags = [];
  10286. 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>');
  10287. 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>');
  10288. 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>');
  10289. 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>`);
  10290. return `
  10291. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 text-xs transition">
  10292. <td class="py-3 px-4">
  10293. <div class="flex items-center gap-2">
  10294. <span class="font-bold text-white text-sm">${escapeHtml(c.interface)}</span>
  10295. ${c.comment ? `<span class="text-[11px] text-slate-400 font-sans italic">(${escapeHtml(c.comment)})</span>` : ''}
  10296. </div>
  10297. </td>
  10298. <td class="py-3 px-4">${statusBadge}</td>
  10299. <td class="py-3 px-4 font-mono">${ipDisplay}</td>
  10300. <td class="py-3 px-4 font-mono">${gwDisplay}</td>
  10301. <td class="py-3 px-4 font-mono">${srvDisplay}</td>
  10302. <td class="py-3 px-4 font-mono text-[11px]">${dnsDisplay}</td>
  10303. <td class="py-3 px-4 font-mono text-[11px]">${expDisplay}</td>
  10304. <td class="py-3 px-4">
  10305. <div class="flex flex-wrap gap-1 font-mono">${flags.join('')}</div>
  10306. </td>
  10307. <td class="py-3 px-4 text-right space-x-1.5 font-sans whitespace-nowrap">
  10308. ${c.enabled ? `
  10309. <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>
  10310. <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>
  10311. <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>
  10312. ` : `
  10313. <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>
  10314. `}
  10315. <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>
  10316. <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>
  10317. </td>
  10318. </tr>
  10319. `;
  10320. }).join('');
  10321. }
  10322. function openDHCPClientModal(clientId = null) {
  10323. const modal = document.getElementById('modal-dhcp-client');
  10324. if (!modal) return;
  10325. const title = document.getElementById('modal-dhcp-title');
  10326. const idInput = document.getElementById('modal-dhcp-id');
  10327. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  10328. const distInput = document.getElementById('modal-dhcp-distance');
  10329. const commentInput = document.getElementById('modal-dhcp-comment');
  10330. const defRouteCheck = document.getElementById('modal-dhcp-def-route');
  10331. const peerDnsCheck = document.getElementById('modal-dhcp-peer-dns');
  10332. const peerNtpCheck = document.getElementById('modal-dhcp-peer-ntp');
  10333. const enabledCheck = document.getElementById('modal-dhcp-enabled');
  10334. // Populate interfaces
  10335. if (ifaceSelect) {
  10336. let opts = '<option value="">Select interface...</option>';
  10337. const allIfaces = state.interfaces || [];
  10338. const allVlans = state.vlans || [];
  10339. const usedIfaces = new Set((state.dhcpClients || []).map(c => c.interface));
  10340. // Group 1: Physical & Bridge Interfaces
  10341. opts += '<optgroup label="Physical & Bridge Interfaces">';
  10342. allIfaces.forEach(i => {
  10343. const isConfigured = usedIfaces.has(i.name) ? ' (Configured)' : '';
  10344. opts += `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} [${escapeHtml(i.role || i.type)}]${isConfigured}</option>`;
  10345. });
  10346. opts += '</optgroup>';
  10347. // Group 2: VLAN Interfaces
  10348. if (allVlans.length > 0) {
  10349. opts += '<optgroup label="802.1Q VLAN Sub-interfaces">';
  10350. allVlans.forEach(v => {
  10351. const isConfigured = usedIfaces.has(v.name) ? ' (Configured)' : '';
  10352. opts += `<option value="${escapeHtml(v.name)}">${escapeHtml(v.name)} (VLAN ${v.vlan_id})${isConfigured}</option>`;
  10353. });
  10354. opts += '</optgroup>';
  10355. }
  10356. ifaceSelect.innerHTML = opts;
  10357. }
  10358. if (clientId) {
  10359. const client = (state.dhcpClients || []).find(c => c.id === clientId);
  10360. if (client) {
  10361. if (title) title.innerText = `Edit DHCP Client: ${client.interface}`;
  10362. if (idInput) idInput.value = client.id;
  10363. if (ifaceSelect) {
  10364. ifaceSelect.value = client.interface;
  10365. ifaceSelect.disabled = true; // interface cannot be changed on edit
  10366. }
  10367. if (distInput) distInput.value = client.default_route_distance || 1;
  10368. if (commentInput) commentInput.value = client.comment || '';
  10369. if (defRouteCheck) defRouteCheck.checked = client.add_default_route !== false;
  10370. if (peerDnsCheck) peerDnsCheck.checked = client.use_peer_dns !== false;
  10371. if (peerNtpCheck) peerNtpCheck.checked = client.use_peer_ntp !== false;
  10372. if (enabledCheck) enabledCheck.checked = client.enabled !== false;
  10373. }
  10374. } else {
  10375. if (title) title.innerText = 'Add DHCP Client';
  10376. if (idInput) idInput.value = '';
  10377. if (ifaceSelect) {
  10378. ifaceSelect.value = '';
  10379. ifaceSelect.disabled = false;
  10380. }
  10381. if (distInput) distInput.value = 1;
  10382. if (commentInput) commentInput.value = '';
  10383. if (defRouteCheck) defRouteCheck.checked = true;
  10384. if (peerDnsCheck) peerDnsCheck.checked = true;
  10385. if (peerNtpCheck) peerNtpCheck.checked = true;
  10386. if (enabledCheck) enabledCheck.checked = true;
  10387. }
  10388. modal.classList.remove('hidden');
  10389. }
  10390. function openDHCPClientModalForIface(ifaceName) {
  10391. openDHCPClientModal();
  10392. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  10393. if (ifaceSelect && ifaceName) {
  10394. ifaceSelect.value = ifaceName;
  10395. }
  10396. }
  10397. function closeDHCPClientModal() {
  10398. const modal = document.getElementById('modal-dhcp-client');
  10399. if (modal) modal.classList.add('hidden');
  10400. }
  10401. async function submitSaveDHCPClient(e) {
  10402. if (e) e.preventDefault();
  10403. const id = document.getElementById('modal-dhcp-id')?.value;
  10404. const iface = document.getElementById('modal-dhcp-iface')?.value?.trim();
  10405. const distance = parseInt(document.getElementById('modal-dhcp-distance')?.value || '1', 10);
  10406. const comment = document.getElementById('modal-dhcp-comment')?.value?.trim() || '';
  10407. const defRoute = document.getElementById('modal-dhcp-def-route')?.checked ?? true;
  10408. const peerDns = document.getElementById('modal-dhcp-peer-dns')?.checked ?? true;
  10409. const peerNtp = document.getElementById('modal-dhcp-peer-ntp')?.checked ?? true;
  10410. const enabled = document.getElementById('modal-dhcp-enabled')?.checked ?? true;
  10411. if (!id && !iface) {
  10412. showToast('Input Required', 'Please select an interface for the DHCP client', 'warning');
  10413. return;
  10414. }
  10415. try {
  10416. let res;
  10417. if (id) {
  10418. // PUT update
  10419. res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  10420. method: 'PUT',
  10421. headers: { 'Content-Type': 'application/json' },
  10422. body: JSON.stringify({
  10423. enabled,
  10424. add_default_route: defRoute,
  10425. default_route_distance: distance,
  10426. use_peer_dns: peerDns,
  10427. use_peer_ntp: peerNtp,
  10428. comment
  10429. })
  10430. });
  10431. } else {
  10432. // POST create
  10433. res = await fetch(`${API_BASE}/dhcp/clients`, {
  10434. method: 'POST',
  10435. headers: { 'Content-Type': 'application/json' },
  10436. body: JSON.stringify({
  10437. interface: iface,
  10438. enabled,
  10439. add_default_route: defRoute,
  10440. default_route_distance: distance,
  10441. use_peer_dns: peerDns,
  10442. use_peer_ntp: peerNtp,
  10443. comment
  10444. })
  10445. });
  10446. }
  10447. const data = await res.json();
  10448. if (!res.ok) {
  10449. showToast('Error', data.error || 'Failed to save DHCP client', 'error');
  10450. return;
  10451. }
  10452. closeDHCPClientModal();
  10453. showToast('Success', id ? 'DHCP Client updated successfully' : `DHCP Client activated on ${iface}`, 'success');
  10454. await loadDHCPClients();
  10455. fetchData(); // refresh interfaces list with new lease/status
  10456. } catch (err) {
  10457. showToast('Error', err.message, 'error');
  10458. }
  10459. }
  10460. async function toggleDHCPClientState(id, enabled) {
  10461. try {
  10462. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/state`, {
  10463. method: 'POST',
  10464. headers: { 'Content-Type': 'application/json' },
  10465. body: JSON.stringify({ enabled })
  10466. });
  10467. const data = await res.json();
  10468. if (!res.ok) {
  10469. showToast('Error', data.error || 'Failed to toggle client state', 'error');
  10470. return;
  10471. }
  10472. showToast('Updated', `DHCP client ${enabled ? 'enabled' : 'disabled'}`, 'info');
  10473. await loadDHCPClients();
  10474. fetchData();
  10475. } catch (err) {
  10476. showToast('Error', err.message, 'error');
  10477. }
  10478. }
  10479. async function renewDHCPClient(id) {
  10480. try {
  10481. showToast('Renewing...', 'Requesting DHCP lease renewal from upstream server', 'info');
  10482. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/renew`, {
  10483. method: 'POST'
  10484. });
  10485. const data = await res.json();
  10486. if (!res.ok) {
  10487. showToast('Error', data.error || 'Failed to renew lease', 'error');
  10488. return;
  10489. }
  10490. showToast('Lease Renewed', 'DHCP renewal signal sent successfully', 'success');
  10491. setTimeout(() => {
  10492. loadDHCPClients();
  10493. fetchData();
  10494. }, 1500);
  10495. } catch (err) {
  10496. showToast('Error', err.message, 'error');
  10497. }
  10498. }
  10499. async function releaseDHCPClient(id) {
  10500. try {
  10501. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/release`, {
  10502. method: 'POST'
  10503. });
  10504. const data = await res.json();
  10505. if (!res.ok) {
  10506. showToast('Error', data.error || 'Failed to release lease', 'error');
  10507. return;
  10508. }
  10509. showToast('Lease Released', 'DHCP lease released from upstream server', 'info');
  10510. await loadDHCPClients();
  10511. fetchData();
  10512. } catch (err) {
  10513. showToast('Error', err.message, 'error');
  10514. }
  10515. }
  10516. async function deleteDHCPClient(id, ifaceName) {
  10517. if (!confirm(`Are you sure you want to remove the DHCP Client on ${ifaceName}? The interface will release its dynamic IP.`)) {
  10518. return;
  10519. }
  10520. try {
  10521. const res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  10522. method: 'DELETE'
  10523. });
  10524. const data = await res.json();
  10525. if (!res.ok) {
  10526. showToast('Error', data.error || 'Failed to delete DHCP client', 'error');
  10527. return;
  10528. }
  10529. showToast('Deleted', `DHCP client removed from ${ifaceName}`, 'info');
  10530. await loadDHCPClients();
  10531. fetchData();
  10532. } catch (err) {
  10533. showToast('Error', err.message, 'error');
  10534. }
  10535. }
  10536. // ==================== UNIVERSAL TABLE ORDERING / SORTING (WINBOX / WEBFIG STYLE) ====================
  10537. function initTableSorting() {
  10538. document.querySelectorAll('table').forEach(setupSortableTable);
  10539. }
  10540. function setupSortableTable(table) {
  10541. const thead = table.querySelector('thead');
  10542. const tbody = table.querySelector('tbody');
  10543. if (!thead || !tbody) return;
  10544. const headerRows = thead.querySelectorAll('tr');
  10545. if (headerRows.length === 0) return;
  10546. const ths = headerRows[headerRows.length - 1].querySelectorAll('th');
  10547. ths.forEach((th, colIdx) => {
  10548. if (th._sortBound) return;
  10549. th._sortBound = true;
  10550. const rawText = th.innerText.trim().toLowerCase();
  10551. const isActionsCol = rawText === 'actions' || (rawText === 'action' && th.classList.contains('text-right'));
  10552. const isCheckboxCol = !!th.querySelector('input[type="checkbox"]');
  10553. const isExpandCol = (th.classList.contains('w-8') || th.classList.contains('w-6')) && !rawText;
  10554. const isExplicitNoSort = th.classList.contains('no-sort') || th.getAttribute('data-sortable') === 'false';
  10555. if (isActionsCol || isCheckboxCol || isExpandCol || isExplicitNoSort) {
  10556. return;
  10557. }
  10558. th.classList.add('table-sortable', 'group');
  10559. if (!th.title) th.title = 'Click to sort (Ascending / Descending / Default)';
  10560. let icon = th.querySelector('.table-sort-icon');
  10561. if (!icon) {
  10562. icon = document.createElement('span');
  10563. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  10564. icon.innerHTML = '⇅';
  10565. th.appendChild(icon);
  10566. }
  10567. th.addEventListener('click', (e) => {
  10568. if (e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON' || e.target.closest('button, input')) return;
  10569. handleHeaderClick(table, th, colIdx);
  10570. });
  10571. });
  10572. if (!tbody._sortObserved) {
  10573. tbody._sortObserved = true;
  10574. let sortDebounceTimer = null;
  10575. const observer = new MutationObserver((mutations) => {
  10576. if (tbody._isSorting) return;
  10577. const hasChildChanges = mutations.some(m => m.type === 'childList' && m.addedNodes.length > 0);
  10578. if (!hasChildChanges) return;
  10579. clearTimeout(sortDebounceTimer);
  10580. sortDebounceTimer = setTimeout(() => {
  10581. if (tbody._isSorting) return;
  10582. if (table._activeSort && table._activeSort.dir !== 'none') {
  10583. applyTableSort(table, table._activeSort.colIdx, table._activeSort.dir, false);
  10584. } else {
  10585. tagOriginalRowOrder(tbody);
  10586. }
  10587. }, 10);
  10588. });
  10589. observer.observe(tbody, { childList: true });
  10590. }
  10591. tagOriginalRowOrder(tbody);
  10592. }
  10593. function tagOriginalRowOrder(tbody) {
  10594. let idx = 0;
  10595. Array.from(tbody.children).forEach(tr => {
  10596. if (!tr.querySelector('td[colspan]')) {
  10597. if (!tr.hasAttribute('data-orig-idx')) {
  10598. tr.setAttribute('data-orig-idx', idx++);
  10599. }
  10600. }
  10601. });
  10602. }
  10603. function handleHeaderClick(table, th, colIdx) {
  10604. const currentSort = table._activeSort || { colIdx: -1, dir: 'none' };
  10605. let newDir = 'asc';
  10606. if (currentSort.colIdx === colIdx) {
  10607. if (currentSort.dir === 'asc') newDir = 'desc';
  10608. else if (currentSort.dir === 'desc') newDir = 'none';
  10609. else newDir = 'asc';
  10610. } else {
  10611. newDir = 'asc';
  10612. }
  10613. table._activeSort = { colIdx, dir: newDir };
  10614. updateHeaderIcons(table, colIdx, newDir);
  10615. applyTableSort(table, colIdx, newDir, true);
  10616. }
  10617. function updateHeaderIcons(table, activeColIdx, dir) {
  10618. const thead = table.querySelector('thead');
  10619. if (!thead) return;
  10620. const ths = thead.querySelectorAll('th');
  10621. ths.forEach((th, idx) => {
  10622. const icon = th.querySelector('.table-sort-icon');
  10623. if (!icon) return;
  10624. if (idx === activeColIdx && dir !== 'none') {
  10625. icon.innerHTML = dir === 'asc' ? '▲' : '▼';
  10626. icon.className = 'table-sort-icon text-cyan-400 font-bold opacity-100';
  10627. th.classList.add('table-sorted-active');
  10628. } else {
  10629. icon.innerHTML = '⇅';
  10630. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  10631. th.classList.remove('table-sorted-active');
  10632. }
  10633. });
  10634. }
  10635. function applyTableSort(table, colIdx, dir, userInitiated) {
  10636. const tbody = table.querySelector('tbody');
  10637. if (!tbody || tbody.children.length <= 1) return;
  10638. tbody._isSorting = true;
  10639. tagOriginalRowOrder(tbody);
  10640. // Group parent rows and any attached drawer/sub-rows
  10641. const groups = [];
  10642. let currentGroup = null;
  10643. Array.from(tbody.children).forEach(tr => {
  10644. if (tr.querySelector('td[colspan]')) {
  10645. if (currentGroup) {
  10646. currentGroup.subRows.push(tr);
  10647. } else {
  10648. groups.push({ mainRow: tr, subRows: [] });
  10649. }
  10650. } else {
  10651. currentGroup = { mainRow: tr, subRows: [] };
  10652. groups.push(currentGroup);
  10653. }
  10654. });
  10655. if (dir === 'none') {
  10656. groups.sort((a, b) => {
  10657. const idxA = parseInt(a.mainRow.getAttribute('data-orig-idx') || '0', 10);
  10658. const idxB = parseInt(b.mainRow.getAttribute('data-orig-idx') || '0', 10);
  10659. return idxA - idxB;
  10660. });
  10661. } else {
  10662. groups.sort((a, b) => {
  10663. const cellA = a.mainRow.children[colIdx];
  10664. const cellB = b.mainRow.children[colIdx];
  10665. const res = compareTableCells(cellA, cellB);
  10666. return dir === 'asc' ? res : -res;
  10667. });
  10668. }
  10669. // Re-append rows in sorted order
  10670. groups.forEach(g => {
  10671. tbody.appendChild(g.mainRow);
  10672. g.subRows.forEach(sub => tbody.appendChild(sub));
  10673. });
  10674. tbody._isSorting = false;
  10675. }
  10676. function getCellRawText(cell) {
  10677. if (!cell) return '';
  10678. if (cell.hasAttribute('data-sort-value')) return cell.getAttribute('data-sort-value');
  10679. const input = cell.querySelector('input, select');
  10680. if (input) {
  10681. if (input.type === 'checkbox') return input.checked ? '1' : '0';
  10682. return input.value;
  10683. }
  10684. return cell.innerText.trim();
  10685. }
  10686. function parseTrafficToNumber(str) {
  10687. const m = str.match(/^([\d.,]+)\s*([KMGTkmgt]?[iI]?[Bb](?:ps|\/s)?)/);
  10688. if (!m) return null;
  10689. const num = parseFloat(m[1].replace(/,/g, ''));
  10690. if (isNaN(num)) return null;
  10691. const unit = m[2].toUpperCase();
  10692. let mult = 1;
  10693. if (unit.startsWith('K')) mult = 1024;
  10694. else if (unit.startsWith('M')) mult = 1024 * 1024;
  10695. else if (unit.startsWith('G')) mult = 1024 * 1024 * 1024;
  10696. else if (unit.startsWith('T')) mult = 1024 * 1024 * 1024 * 1024;
  10697. return num * mult;
  10698. }
  10699. function parseIpToNumber(str) {
  10700. const clean = str.replace(/^[!~]/, '').trim();
  10701. const m = clean.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,2}))?/);
  10702. if (!m) return null;
  10703. const o1 = parseInt(m[1], 10);
  10704. const o2 = parseInt(m[2], 10);
  10705. const o3 = parseInt(m[3], 10);
  10706. const o4 = parseInt(m[4], 10);
  10707. if (o1 > 255 || o2 > 255 || o3 > 255 || o4 > 255) return null;
  10708. return ((o1 * 256 + o2) * 256 + o3) * 256 + o4;
  10709. }
  10710. function parseCompoundPackets(str) {
  10711. const m = str.match(/^([\d,]+)p/);
  10712. if (!m) return null;
  10713. return parseInt(m[1].replace(/,/g, ''), 10);
  10714. }
  10715. function compareTableCells(cellA, cellB) {
  10716. const a = getCellRawText(cellA);
  10717. const b = getCellRawText(cellB);
  10718. if (a === '' && b !== '') return 1;
  10719. if (b === '' && a !== '') return -1;
  10720. if (a === b) return 0;
  10721. // 1. IP Addresses / CIDR
  10722. const ipA = parseIpToNumber(a);
  10723. const ipB = parseIpToNumber(b);
  10724. if (ipA !== null && ipB !== null) return ipA - ipB;
  10725. // 2. Packet counts (e.g. "1,250p / 45 KB")
  10726. const pktA = parseCompoundPackets(a);
  10727. const pktB = parseCompoundPackets(b);
  10728. if (pktA !== null && pktB !== null) return pktA - pktB;
  10729. // 3. Traffic / Throughput / Bytes (e.g. "1.2 MB", "500 KiB", "10 Gbps")
  10730. const trafA = parseTrafficToNumber(a);
  10731. const trafB = parseTrafficToNumber(b);
  10732. if (trafA !== null && trafB !== null) return trafA - trafB;
  10733. // 4. Numbers with '#' or formatted with commas (e.g. "#1", "24", "1,200")
  10734. const cleanNumA = a.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  10735. const cleanNumB = b.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  10736. const numA = Number(cleanNumA);
  10737. const numB = Number(cleanNumB);
  10738. if (!isNaN(numA) && !isNaN(numB) && cleanNumA !== '' && cleanNumB !== '') {
  10739. return numA - numB;
  10740. }
  10741. // 5. Natural case-insensitive string compare
  10742. return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
  10743. }
  10744. // Global observer for dynamically injected tables (e.g. inside modals or drawers)
  10745. if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {
  10746. const docTableObserver = new MutationObserver((mutations) => {
  10747. let needsInit = false;
  10748. for (const m of mutations) {
  10749. for (const node of m.addedNodes) {
  10750. if (node.nodeType === 1) {
  10751. if (node.tagName === 'TABLE' || (node.querySelector && node.querySelector('table'))) {
  10752. needsInit = true;
  10753. break;
  10754. }
  10755. }
  10756. }
  10757. if (needsInit) break;
  10758. }
  10759. if (needsInit) {
  10760. initTableSorting();
  10761. }
  10762. });
  10763. docTableObserver.observe(document.body || document.documentElement, { childList: true, subtree: true });
  10764. }