| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442 |
- // DebTik - Debian Linux Router Frontend Application Logic
- // ================= Interceptor: Automatic Auth Bearer & 401 Handling =================
- const originalFetch = window.fetch.bind(window);
- const pendingAPIReads = new Map();
- const telemetryHealth = { lastSuccess: 0, failures: new Map() };
- let coreRefreshPromise = null;
- let lastSummaryRefresh = 0;
- function renderTelemetryHealth() {
- const el = document.getElementById('telemetry-health');
- if (!el) return;
- const failures = [...telemetryHealth.failures.entries()];
- const seconds = telemetryHealth.lastSuccess ? Math.floor((Date.now() - telemetryHealth.lastSuccess) / 1000) : null;
- const stale = seconds === null || seconds > 15;
- el.textContent = failures.length ? `Data unavailable / incomplete${seconds === null ? '' : ` · updated ${seconds}s ago`}` : stale ? 'Waiting for fresh data' : `Updated ${seconds}s ago`;
- el.className = `text-[10px] font-mono ${failures.length || stale ? 'text-amber-400' : 'text-emerald-400'}`;
- el.title = failures.length ? failures.map(([path, error]) => `${path}: ${error}`).join('\n') : telemetryHealth.lastSuccess ? `Last successful update: ${new Date(telemetryHealth.lastSuccess).toLocaleTimeString()}` : 'No successful update yet';
- }
- function stopSessionPolling() {
- if (window._telemetryInterval) clearInterval(window._telemetryInterval);
- window._telemetryInterval = null;
- if (trafficEventSource) trafficEventSource.close();
- trafficEventSource = null;
- if (trafficPollFallback) clearInterval(trafficPollFallback);
- trafficPollFallback = null;
- if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
- bwtestState.pollTimer = null;
- if (logsTimer) clearInterval(logsTimer);
- logsTimer = null;
- stopFwStatPolling();
- stopNATStatPolling();
- stopMangleStatPolling();
- telemetryHealth.failures.clear();
- telemetryHealth.lastSuccess = 0;
- lastSummaryRefresh = 0;
- }
- window.fetch = async function(resource, options = {}) {
- const url = new URL(resource instanceof Request ? resource.url : resource, window.location.href);
- const isAPI = url.origin === window.location.origin && url.pathname.startsWith('/api/');
- if (!isAPI) return originalFetch(resource, options);
- const config = { ...options, headers: new Headers(options.headers || (resource instanceof Request ? resource.headers : undefined)) };
- const token = localStorage.getItem('debtik_token');
- if (token && !config.headers.has('Authorization')) config.headers.set('Authorization', `Bearer ${token}`);
- const method = (config.method || (resource instanceof Request ? resource.method : 'GET')).toUpperCase();
- const isRead = method === 'GET' && !url.pathname.includes('/stream') && !url.pathname.startsWith('/api/auth/');
- const key = `${url.href}|${JSON.stringify([...config.headers])}`;
- if (isRead && pendingAPIReads.has(key)) return (await pendingAPIReads.get(key)).clone();
- const perform = async () => {
- let timeout;
- if (isRead && !config.signal) {
- const controller = new AbortController();
- config.signal = controller.signal;
- timeout = setTimeout(() => controller.abort(), 15000);
- }
- try {
- const response = await originalFetch(resource, config);
- if (isRead) {
- if (response.ok) {
- telemetryHealth.lastSuccess = Date.now();
- telemetryHealth.failures.delete(url.pathname);
- } else {
- telemetryHealth.failures.set(url.pathname, `HTTP ${response.status}; displayed values may be old`);
- }
- renderTelemetryHealth();
- }
- if (response.status === 401 && url.pathname !== '/api/auth/login' && state.currentUser && token === localStorage.getItem('debtik_token')) {
- stopSessionPolling();
- state.isPolling = false;
- state.currentUser = null;
- localStorage.removeItem('debtik_token');
- showLoginScreen(true);
- }
- return response;
- } catch (err) {
- if (isRead) {
- telemetryHealth.failures.set(url.pathname, err.name === 'AbortError' ? 'Request timed out' : 'Connection failed; displayed values may be old');
- renderTelemetryHealth();
- }
- throw err;
- } finally {
- if (timeout) clearTimeout(timeout);
- }
- };
- if (!isRead) return perform();
- const request = perform();
- pendingAPIReads.set(key, request);
- try { return (await request).clone(); }
- finally { if (pendingAPIReads.get(key) === request) pendingAPIReads.delete(key); }
- };
- let state = {
- currentUser: null,
- users: [],
- interfaces: [],
- vlans: [],
- systemStatus: null,
- vpnStatus: null,
- routes: [],
- activeTab: 'dashboard',
- fwSubTab: 'filter',
- bridgeSubTab: 'bridges',
- bridges: [],
- bridgePorts: [],
- bridgeVLANs: [],
- bridgeHosts: [],
- bridgeSummary: null,
- routesSubTab: 'routes',
- pppSubTab: 'secrets',
- eoipTunnels: [],
- vxlanTunnels: [],
- vxlanVteps: [],
- pppSecrets: [],
- pppProfiles: [],
- pppActiveSessions: [],
- pppoeServer: null,
- pptpServer: null,
- l2tpServer: null,
- ipsecServer: null,
- ifaceFilter: 'all',
- currentModalIface: null,
- isPolling: false,
- expandedParents: new Set(['eth0']),
- pppoeData: null,
- wgData: null,
- ipsecData: null,
- l2tpData: null,
- pptpData: null,
- fwSummary: null,
- filterRules: [],
- natRules: [],
- mangleRules: [],
- addressLists: [],
- connections: [],
- policyRules: [],
- routingTables: [],
- routingFilters: [],
- filterChainSelected: 'all',
- activeToolsSubTab: 'ping',
- dhcpClients: [],
- dhcpSummary: null,
- dhcpServerTab: 'servers',
- dhcpServers: [],
- dhcpNetworks: [],
- dhcpLeases: [],
- dhcpOptions: [],
- dhcpServerSummary: null,
- sdwanGroups: [],
- sdwanTelemetry: null
- };
- const API_BASE = '/api';
- function escapeHtml(str) {
- if (str === null || str === undefined) return '';
- return String(str)
- .replace(/&/g, '&')
- .replace(/</g, '<')
- .replace(/>/g, '>')
- .replace(/"/g, '"')
- .replace(/'/g, ''');
- }
- function formatBytes(bytes) {
- if (bytes === undefined || bytes === null || isNaN(bytes) || bytes === 0) return '0 B';
- const k = 1024;
- const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
- const i = Math.floor(Math.log(bytes) / Math.log(k));
- if (i < 0 || i >= sizes.length) return `${bytes} B`;
- return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`;
- }
- // Initialize on page load
- document.addEventListener('DOMContentLoaded', async () => {
- initTableSorting();
- // Verify authentication before bootstrapping telemetry and views
- const isAuthenticated = await checkAuthStatus();
- if (isAuthenticated) {
- const hash = window.location.hash.replace('#', '') || 'dashboard';
- navigate(hash);
- // Full state telemetry polling every 5 seconds (smooth & flicker-free)
- if (!window._telemetryInterval) {
- window._telemetryInterval = setInterval(() => {
- if (state.isPolling && state.currentUser && !document.hidden) {
- fetchData(false);
- }
- }, 5000);
- }
- }
- });
- let trafficEventSource = null;
- let trafficPollFallback = null;
- function initLiveTrafficStream() {
- if (trafficEventSource) {
- try { trafficEventSource.close(); } catch(e) {}
- trafficEventSource = null;
- }
- if (trafficPollFallback) {
- clearInterval(trafficPollFallback);
- trafficPollFallback = null;
- }
- if (window.EventSource) {
- try {
- trafficEventSource = new EventSource(`${API_BASE}/interfaces/traffic/stream`);
- trafficEventSource.onmessage = (event) => {
- try {
- const data = JSON.parse(event.data);
- updateLiveInterfaceTraffic(data);
- } catch (e) {
- console.error('Error parsing live traffic event:', e);
- }
- };
- trafficEventSource.onerror = () => {
- // Fallback polling if SSE disconnects
- if (!trafficPollFallback) {
- trafficPollFallback = setInterval(pollLiveTrafficSnapshot, 1000);
- }
- };
- trafficEventSource.onopen = () => {
- if (trafficPollFallback) {
- clearInterval(trafficPollFallback);
- trafficPollFallback = null;
- }
- };
- return;
- } catch (e) {
- console.warn('EventSource failed, using 1s polling fallback:', e);
- }
- }
- // Fallback if EventSource is unavailable
- trafficPollFallback = setInterval(pollLiveTrafficSnapshot, 1000);
- }
- async function pollLiveTrafficSnapshot() {
- try {
- const res = await fetch(`${API_BASE}/interfaces/traffic/rates`);
- if (res.ok) {
- const data = await res.json();
- updateLiveInterfaceTraffic(data);
- }
- } catch (e) {}
- }
- function updateLiveInterfaceTraffic(data) {
- if (!data || !data.interfaces) return;
- state.latestTraffic = data;
- // 1. Update Top & Dashboard Total Bandwidth Indicators
- const rxHuman = data.total_rx_human || '0 B/s';
- const txHuman = data.total_tx_human || '0 B/s';
- const statRx = document.getElementById('stat-traffic-rx');
- if (statRx && statRx.innerText !== rxHuman) statRx.innerText = rxHuman;
- const statTx = document.getElementById('stat-traffic-tx');
- if (statTx && statTx.innerText !== txHuman) statTx.innerText = txHuman;
- // 2. Update state.interfaces rates in-memory
- if (Array.isArray(state.interfaces)) {
- state.interfaces.forEach(i => {
- const live = data.interfaces[i.name];
- if (live) {
- i.rate = {
- rx_bytes_sec: live.rx_bytes_sec,
- tx_bytes_sec: live.tx_bytes_sec,
- rx_human: live.rx_human,
- tx_human: live.tx_human
- };
- i.stats = {
- rx_bytes: live.rx_bytes,
- tx_bytes: live.tx_bytes,
- rx_packets: live.rx_packets,
- tx_packets: live.tx_packets,
- rx_errors: live.rx_errors,
- tx_errors: live.tx_errors,
- rx_dropped: live.rx_dropped,
- tx_dropped: live.tx_dropped
- };
- }
- });
- }
- // 3. Update all live UI rate spans in-place (ZERO flicker)
- Object.keys(data.interfaces).forEach(name => {
- const live = data.interfaces[name];
- // Dashboard Port Matrix Card
- const cardRate = document.getElementById(`port-card-rate-${name}`);
- if (cardRate && cardRate.innerText !== live.rx_human) {
- cardRate.innerText = live.rx_human;
- }
- // Dashboard Quick Interfaces Table
- const quickRx = document.getElementById(`quick-rx-${name}`);
- if (quickRx) quickRx.innerText = `↓ ${live.rx_human}`;
- const quickTx = document.getElementById(`quick-tx-${name}`);
- if (quickTx) quickTx.innerText = `↑ ${live.tx_human}`;
- // Main Interfaces Tree Table
- const ifaceRx = document.getElementById(`iface-rate-rx-${name}`);
- if (ifaceRx) ifaceRx.innerText = `↓ ${live.rx_human}`;
- const ifaceTx = document.getElementById(`iface-rate-tx-${name}`);
- if (ifaceTx) ifaceTx.innerText = `↑ ${live.tx_human}`;
- // VLAN Sub-interfaces Table
- const vlanRx = document.getElementById(`vlan-rate-rx-${name}`);
- if (vlanRx) vlanRx.innerText = `↓ ${live.rx_human}`;
- const vlanTx = document.getElementById(`vlan-rate-tx-${name}`);
- if (vlanTx) vlanTx.innerText = `↑ ${live.tx_human}`;
- // VLAN Page Table
- const vlanPageRx = document.getElementById(`vlan-page-rate-rx-${name}`);
- if (vlanPageRx) vlanPageRx.innerText = `↓ ${live.rx_human}`;
- const vlanPageTx = document.getElementById(`vlan-page-rate-tx-${name}`);
- if (vlanPageTx) vlanPageTx.innerText = `↑ ${live.tx_human}`;
- });
- }
- // Navigation Handler
- function navigate(tabName) {
- if (tabName === 'dynamic-routing' || tabName === 'routing') {
- navigate('bgp');
- return;
- }
- if (tabName === 'vlans') {
- navigate('interfaces');
- return;
- }
- if (tabName === 'persistence') {
- navigate('dashboard');
- return;
- }
- stopFwStatPolling();
- stopNATStatPolling();
- stopMangleStatPolling();
- state.activeTab = tabName;
- window.location.hash = tabName;
- // Update nav links styling
- document.querySelectorAll('.nav-link').forEach(link => {
- 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';
- });
- const activeNav = document.getElementById(`nav-${tabName}`);
- if (activeNav) {
- 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';
- }
- // Update page headers
- const titles = {
- dashboard: { title: 'Dashboard Overview', sub: 'Live router performance and network telemetry' },
- interfaces: { title: 'Network Interfaces', sub: 'Interface Table View' },
- 'dhcp-client': { title: 'DHCP Client', sub: 'DHCP Client List' },
- 'dhcp-server': { title: 'DHCP Server & Subnets', sub: 'DHCP Server instances, subnet networks (NTP, TFTP, DNS), dynamic leases & static reservations' },
- bridge: { title: 'Bridge Interfaces', sub: 'IEEE 802.1D / 802.1Q VLAN-aware Layer 2 switching, RSTP & hardware forwarding (FDB)' },
- vlans: { title: 'VLAN Virtual Networks', sub: 'IEEE 802.1Q sub-interface segmentation and routing' },
- firewall: { title: 'Network Firewall', sub: 'Stateful packet inspection, NAT, traffic mangle, address lists & connection tracking' },
- routes: { title: 'Routing & Policy', sub: 'Routing tables, static routes (DAS/DAC), and policy routing rules' },
- sdwan: { title: 'Software-Defined WAN (SD-WAN)', sub: 'Multi-link aggregation, traffic load balancing & quality SLA health monitoring' },
- bgp: { title: 'BGP Dynamic Routing', sub: 'BGP multi-instance peering sessions, advertised networks, and routing table (RIB)' },
- ospf: { title: 'OSPF Dynamic Routing', sub: 'OSPFv2 link-state routing, dynamic neighbor adjacencies, and multi-area topology' },
- 'routing-filters': { title: 'Routing Policy Filters', sub: 'Route filter chains, prefix matching, BGP community maps & policy-based path control' },
- 'dynamic-routing': { title: 'BGP Dynamic Routing', sub: 'Dynamic routing engine and peering sessions' },
- ppp: { title: 'PPP Servers & Secrets', sub: 'Subscriber authentication, dynamic IP pools and VPN access concentrators' },
- eoip: { title: 'EoIP Tunnels', sub: 'Ethernet over IP (EoIP / GRETAP) Layer 2 encapsulation & transparent network bridging' },
- vxlan: { title: 'VXLAN Tunnels', sub: 'Virtual Extensible LAN (RFC 7348) Layer 2 overlay networks and static VTEPs' },
- aerotun: { title: 'AeroTUN High-Speed VPN', sub: 'Layer 3 encrypted tunnel with XChaCha20-Poly1305 and adaptive LZ4 compression' },
- pppoe: { title: 'PPPoE Client WAN', sub: 'Point-to-Point Protocol over Ethernet WAN access' },
- wireguard: { title: 'WireGuard VPN', sub: 'High-performance cryptographic Layer 3 tunnels with ChaCha20-Poly1305 key exchange' },
- ipsec: { title: 'IPSec (IKEv2) strongSwan', sub: 'Enterprise Site-to-Site & Roadwarrior IPSec controller' },
- l2tp: { title: 'L2TP VPN Client', sub: 'Layer 2 Tunneling Protocol via xl2tpd' },
- pptp: { title: 'PPTP VPN Client', sub: 'Point-to-Point Tunneling Protocol with MPPE-128 encryption' },
- vrrp: { title: 'VRRP High Availability', sub: 'Virtual Router Redundancy Protocol, active-backup gateway failover & Virtual IP (VIP) routing' },
- bwtest: { title: 'Bandwidth Test Benchmark', sub: 'High-speed line-rate throughput benchmark, token-bucket rate limiting, loss & jitter telemetry' },
- tools: { title: 'Diagnostic & Troubleshooting Tools', sub: 'Network latency analysis, ICMP/MTR telemetry, path tracing, DNS resolution and TCP probing' },
- settings: { title: 'Router Settings & DNS', sub: 'System DNS forwarder, upstream resolvers, static host mappings, and appliance identity' },
- users: { title: 'Local User Manager', sub: 'Manage local system administrator credentials and access permissions' },
- certificates: { title: 'Certificates & SSL/TLS', sub: 'Root Certificate Authorities (CA), Server/Client certificates and automated Let\'s Encrypt' },
- reverse_proxy: { title: 'Reverse Proxy & Gateway', sub: 'HTTP/HTTPS Path Routing, Domain Forwarding & SSL Termination' },
- services: { title: 'Management Services', sub: 'Enable or disable Web, SSH, and Telnet management listeners and listening ports' },
- updates: { title: 'Git Updates', sub: 'Check, install and restore appliance software' },
- logs: { title: 'System Activity Logs', sub: 'Real-time circular buffer log viewer and topic-based event monitoring' }
- };
- const header = titles[tabName] || titles.dashboard;
- const pTitle = document.getElementById('page-title');
- if (pTitle) pTitle.innerText = header.title;
- const pSub = document.getElementById('page-subtitle');
- if (pSub) pSub.innerText = header.sub;
- // Toggle sections dynamically for all section elements
- document.querySelectorAll('main section[id^="section-"]').forEach(el => {
- if (el.id === `section-${tabName}`) {
- el.classList.remove('hidden');
- } else {
- el.classList.add('hidden');
- }
- });
- if (tabName === 'interfaces') {
- loadRoles();
- if (state.activeIfaceSubTab === 'roles') switchIfaceSubTab('roles');
- else switchIfaceSubTab('tree');
- }
- if (tabName === 'bridge') loadBridge();
- if (tabName === 'firewall') loadFirewall();
- if (tabName === 'routes') loadRoutes();
- if (tabName === 'sdwan') loadSDWAN();
- if (tabName === 'bgp') {
- loadDynamicRouting();
- switchBgpSubTab(state.activeBgpSubTab || 'bgp-peers');
- }
- if (tabName === 'ospf') {
- loadDynamicRouting();
- switchOspfTab(state.activeOspfTab || 'instances');
- }
- if (tabName === 'routing-filters') loadDynamicRouting();
- if (tabName === 'dynamic-routing') loadDynamicRouting();
- if (tabName === 'ppp') loadPPP();
- if (tabName === 'eoip') loadEoIP();
- if (tabName === 'vxlan') loadVXLAN();
- if (tabName === 'aerotun') loadAeroTUN();
- if (tabName === 'pppoe') loadPPPoE();
- if (tabName === 'wireguard') loadWireGuard();
- if (tabName === 'ipsec') loadIPSec();
- if (tabName === 'l2tp') loadL2TP();
- if (tabName === 'pptp') loadPPTP();
- if (tabName === 'tools') loadToolsView();
- if (tabName === 'dhcp-client') loadDHCPClients();
- if (tabName === 'dhcp-server') loadDHCPServer();
- if (tabName === 'vrrp') loadVRRP();
- if (tabName === 'bwtest') loadBwTestView();
- if (tabName === 'settings') loadSettingsData();
- if (tabName === 'users') loadUsers();
- if (tabName === 'certificates') loadCertificates();
- if (tabName === 'reverse_proxy') loadReverseProxy();
- if (tabName === 'services') loadServices();
- if (tabName === 'updates') loadUpdateStatus();
- if (tabName === 'logs') loadLogs();
- setTimeout(initTableSorting, 50);
- }
- // Fetch all core system, network and VPN telemetry
- function fetchData(isManual = false) {
- if (coreRefreshPromise) return coreRefreshPromise;
- coreRefreshPromise = refreshCoreData(isManual).finally(() => { coreRefreshPromise = null; });
- return coreRefreshPromise;
- }
- async function refreshCoreData(isManual = false) {
- const spinner = document.getElementById('refresh-spinner');
- if (isManual && spinner) spinner.classList.add('animate-spin');
- try {
- const refreshSummaries = isManual || Date.now() - lastSummaryRefresh > 30000;
- const summaryFetch = path => (refreshSummaries || (state.activeTab === 'interfaces' && ['/vlans', '/roles'].includes(path))) ? fetch(`${API_BASE}${path}`).catch(() => ({ ok: false })) : Promise.resolve({ ok: false });
- const [statusRes, ifacesRes, vlansRes, vpnRes, fwRes, dynRes, brSummaryRes, dhcpSumRes, dhcpClientsRes, vrrpSumRes, rolesRes] = await Promise.all([
- fetch(`${API_BASE}/system/status`).catch(() => ({ ok: false })),
- fetch(`${API_BASE}/interfaces`).catch(() => ({ ok: false })),
- summaryFetch('/vlans'),
- summaryFetch('/vpn/status'),
- summaryFetch('/firewall/summary'),
- summaryFetch('/routing/dynamic/summary'),
- summaryFetch('/bridge/summary'),
- summaryFetch('/dhcp/clients/summary'),
- summaryFetch('/dhcp/clients'),
- summaryFetch('/vrrp/summary').catch(() => null),
- summaryFetch('/roles').catch(() => null)
- ]);
- if (refreshSummaries && [vlansRes, vpnRes, fwRes, dynRes, brSummaryRes, dhcpSumRes, dhcpClientsRes, vrrpSumRes, rolesRes].every(r => r && r.ok)) lastSummaryRefresh = Date.now();
- if (rolesRes && rolesRes.ok) {
- state.roles = await rolesRes.json();
- const countEl = document.getElementById('badge-roles-count');
- if (countEl) countEl.innerText = (state.roles || []).length;
- }
- if (vrrpSumRes && vrrpSumRes.ok) {
- state.vrrpSummary = await vrrpSumRes.json();
- renderVRRPSummary();
- }
- if (dhcpSumRes && dhcpSumRes.ok) {
- state.dhcpSummary = await dhcpSumRes.json();
- const bDhcp = document.getElementById('badge-dhcp-client-count');
- if (bDhcp) bDhcp.innerText = state.dhcpSummary?.total_clients || 0;
- }
- if (dhcpClientsRes && dhcpClientsRes.ok) {
- state.dhcpClients = await dhcpClientsRes.json();
- }
- if (brSummaryRes.ok) {
- state.bridgeSummary = await brSummaryRes.json();
- const bBridge = document.getElementById('badge-bridge-count');
- if (bBridge) bBridge.innerText = state.bridgeSummary?.bridges_count || 0;
- const sBr = document.getElementById('bridge-stat-bridges');
- if (sBr) sBr.innerText = state.bridgeSummary?.bridges_count || 0;
- const sPorts = document.getElementById('bridge-stat-ports');
- if (sPorts) sPorts.innerText = state.bridgeSummary?.ports_count || 0;
- const sHosts = document.getElementById('bridge-stat-hosts');
- if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
- }
- if (statusRes.ok) state.systemStatus = await statusRes.json();
- if (ifacesRes.ok) {
- const ifacesData = await ifacesRes.json();
- const rawIfaces = Array.isArray(ifacesData) ? ifacesData : [];
- state.interfaces = rawIfaces.filter(i => {
- if (!i.name) return false;
- if (i.name.startsWith('ep_')) return false;
- return !['gre0', 'gretap0', 'erspan0', 'sit0', 'tunl0', 'ip6tnl0', 'ip6gre0', 'ip6erspan0'].includes(i.name);
- });
- try { populateToolsInterfaces(); } catch (e) {}
- }
- if (vlansRes.ok) {
- const vlansData = await vlansRes.json();
- state.vlans = Array.isArray(vlansData) ? vlansData : [];
- }
- if (vpnRes.ok) state.vpnStatus = await vpnRes.json();
- if (fwRes && fwRes.ok) state.fwSummary = await fwRes.json();
- if (dynRes && dynRes.ok) state.dynSummary = await dynRes.json();
- updateSystemMetrics();
- updateBadges();
- if (state.activeTab === 'dashboard') renderDashboard();
- if (state.activeTab === 'interfaces') {
- if (state.activeIfaceSubTab === 'roles') renderRolesTable();
- else renderInterfacesList();
- }
- if (state.activeTab === 'vlans') renderVlansList();
- if (state.activeTab === 'firewall') await loadFirewall(false);
- if (state.activeTab === 'routes') await loadRoutes(false);
- if (state.activeTab === 'dynamic-routing' || state.activeTab === 'bgp' || state.activeTab === 'ospf') await loadDynamicRouting(false);
- if (state.activeTab === 'ppp') await loadPPP(false);
- if (state.activeTab === 'eoip') await loadEoIP(false);
- if (state.activeTab === 'vxlan') await loadVXLAN(false);
- if (state.activeTab === 'aerotun') await loadAeroTUN(false);
- if (state.activeTab === 'pppoe') await loadPPPoE(false);
- if (state.activeTab === 'wireguard') await loadWireGuard(false);
- if (state.activeTab === 'ipsec') await loadIPSec(false);
- if (state.activeTab === 'l2tp') await loadL2TP(false);
- if (state.activeTab === 'pptp') await loadPPTP(false);
- if (state.activeTab === 'dhcp-client') await loadDHCPClients(false);
- if (state.activeTab === 'dhcp-server') await loadDHCPServer(false);
- if (state.activeTab === 'vrrp') await loadVRRP(false);
- if (state.activeTab === 'settings') await loadSettingsData(false);
- if (state.activeTab === 'users') await loadUsers(false);
- if (state.activeTab === 'certificates') await loadCertificates(false);
- if (state.activeTab === 'reverse_proxy') await loadReverseProxy(false);
- if (state.activeTab === 'sdwan') await loadSDWAN(false);
- if (state.activeTab === 'services') await loadServices(false);
- if (state.activeTab === 'updates') await loadUpdateStatus(false);
- if (state.activeTab === 'bwtest') await fetchBwTestServerStatus();
- } catch (err) {
- console.error('Failed to fetch router state:', err);
- } finally {
- if (isManual && spinner) {
- setTimeout(() => spinner.classList.remove('animate-spin'), 300);
- }
- }
- }
- // Update Top KPI and Sidebar Telemetry
- function updateSystemMetrics() {
- const s = state.systemStatus;
- const v = state.vpnStatus;
- if (!s) return;
- // Sidebar Host & Uptime
- const sideHost = document.getElementById('side-hostname');
- if (sideHost) sideHost.innerText = s.hostname || 'debian-lxc';
- const sideUp = document.getElementById('side-uptime');
- if (sideUp) sideUp.innerText = s.uptime_human || '0m';
- const sideGw = document.getElementById('side-gateway-ip');
- if (sideGw) sideGw.innerText = s.default_gateway ? `GW: ${s.default_gateway}` : 'GW: Isolated';
- // Compute CPU Metrics
- let cpuPct = 0;
- if (s.cpu_pct !== undefined) {
- cpuPct = s.cpu_pct;
- } else if (s.cpu_load && s.cpu_load.length > 0) {
- const cores = s.cpu_cores || 1;
- cpuPct = Math.min(100, Math.round((parseFloat(s.cpu_load[0]) / cores) * 100));
- }
- const cpuPctStr = `${cpuPct.toFixed(1)}%`;
- const cpuWidth = `${Math.max(3, Math.min(100, cpuPct))}%`;
- const loadStr = s.cpu_load ? s.cpu_load.join(', ') : '-';
- // Sidebar CPU
- const sideCpuVal = document.getElementById('side-cpu-val');
- if (sideCpuVal) sideCpuVal.innerText = cpuPctStr;
- const sideCpuBar = document.getElementById('side-cpu-bar');
- if (sideCpuBar) {
- sideCpuBar.style.width = cpuWidth;
- sideCpuBar.title = `Container: ${cpuPctStr} | Host Loadavg: ${loadStr} (${s.cpu_cores || 1} cores)`;
- }
- // Dashboard CPU Card
- const dashCpuVal = document.getElementById('dash-cpu-val');
- if (dashCpuVal) dashCpuVal.innerText = cpuPctStr;
- const dashCpuBar = document.getElementById('dash-cpu-bar');
- if (dashCpuBar) {
- dashCpuBar.style.width = cpuWidth;
- if (cpuPct > 85) {
- dashCpuBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
- } else if (cpuPct > 65) {
- dashCpuBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
- } else {
- dashCpuBar.className = 'h-full rounded-full bg-emerald-500 transition-all duration-500';
- }
- }
- const dashCpuCores = document.getElementById('dash-cpu-cores');
- if (dashCpuCores) dashCpuCores.innerText = `${s.cpu_cores || 1} Cores`;
- const dashCpuLoad = document.getElementById('dash-cpu-load');
- if (dashCpuLoad) dashCpuLoad.innerText = loadStr;
- const dashCpuStatus = document.getElementById('dash-cpu-status');
- if (dashCpuStatus) {
- if (cpuPct > 85) {
- dashCpuStatus.innerText = 'High';
- dashCpuStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
- } else if (cpuPct > 65) {
- dashCpuStatus.innerText = 'Heavy';
- dashCpuStatus.className = 'text-[11px] font-semibold text-amber-400 uppercase px-2 py-0.5 rounded bg-amber-500/10';
- } else {
- dashCpuStatus.innerText = 'Normal';
- dashCpuStatus.className = 'text-[11px] font-semibold text-emerald-400 uppercase px-2 py-0.5 rounded bg-emerald-500/10';
- }
- }
- // Compute RAM Metrics
- const memPct = Math.round(s.mem_usage_pct || 0);
- const memPctStr = `${memPct}%`;
- const memWidth = `${Math.max(3, Math.min(100, memPct))}%`;
- const usedMB = s.mem_used_mb || 0;
- const totalMB = s.mem_total_mb || 0;
- const freeMB = totalMB > usedMB ? totalMB - usedMB : 0;
- function fmtMemMB(mb) {
- if (mb >= 1024) {
- return `${(mb / 1024).toFixed(1)} GB`;
- }
- return `${mb} MB`;
- }
- // Sidebar RAM
- const sideRamVal = document.getElementById('side-ram-val');
- if (sideRamVal) sideRamVal.innerText = memPctStr;
- const sideRamBar = document.getElementById('side-ram-bar');
- if (sideRamBar) sideRamBar.style.width = memWidth;
- // Dashboard RAM Card
- const dashRamVal = document.getElementById('dash-ram-val');
- if (dashRamVal) dashRamVal.innerText = memPctStr;
- const dashRamBar = document.getElementById('dash-ram-bar');
- if (dashRamBar) {
- dashRamBar.style.width = memWidth;
- if (memPct > 85) {
- dashRamBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
- } else if (memPct > 70) {
- dashRamBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
- } else {
- dashRamBar.className = 'h-full rounded-full bg-indigo-500 transition-all duration-500';
- }
- }
- const dashRamUsedTotal = document.getElementById('dash-ram-used-total');
- if (dashRamUsedTotal) {
- dashRamUsedTotal.innerText = `${fmtMemMB(usedMB)} / ${fmtMemMB(totalMB)}`;
- }
- const dashRamFree = document.getElementById('dash-ram-free');
- if (dashRamFree) {
- dashRamFree.innerText = fmtMemMB(freeMB);
- }
- const dashRamStatus = document.getElementById('dash-ram-status');
- if (dashRamStatus) {
- if (memPct > 85) {
- dashRamStatus.innerText = 'High';
- dashRamStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
- } else {
- dashRamStatus.innerText = 'Active';
- dashRamStatus.className = 'text-[11px] font-semibold text-indigo-400 uppercase px-2 py-0.5 rounded bg-indigo-500/10';
- }
- }
- // Legacy Dashboard Stats (Safe checks)
- const elIfacesUp = document.getElementById('stat-ifaces-up');
- if (elIfacesUp) elIfacesUp.innerText = s.up_ifaces || 0;
- const elIfacesTot = document.getElementById('stat-ifaces-total');
- if (elIfacesTot) elIfacesTot.innerText = `${s.total_ifaces || 0} Total`;
- const elIfacesDown = document.getElementById('stat-ifaces-down');
- if (elIfacesDown) elIfacesDown.innerText = `${s.down_ifaces || 0} DOWN`;
- const elVlans = document.getElementById('stat-vlans-count');
- if (elVlans) elVlans.innerText = s.vlan_ifaces || 0;
- // VPN Status Indicators
- if (v) {
- const totalActive = v.total_active_tunnels || 0;
- const statVpnActive = document.getElementById('stat-vpn-active');
- if (statVpnActive) statVpnActive.innerText = totalActive;
- const tunnelsDot = document.getElementById('tunnels-dot');
- const tunnelsLabel = document.getElementById('tunnels-label');
- if (tunnelsDot && tunnelsLabel) {
- if (totalActive > 0) {
- tunnelsDot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
- tunnelsLabel.innerText = `${totalActive} Active VPN Tunnel${totalActive > 1 ? 's' : ''}`;
- } else {
- tunnelsDot.className = 'w-2 h-2 rounded-full bg-slate-500';
- tunnelsLabel.innerText = '0 Active VPN Tunnels';
- }
- }
- setDotBadge('badge-pppoe-status', (v.active_pppoe || 0) > 0 || v.pppoe_connected);
- setDotBadge('badge-wg-status', (v.active_wireguard || 0) > 0 || v.wireguard_active);
- setDotBadge('badge-ipsec-status', (v.active_ipsec || 0) > 0 || v.ipsec_active);
- setDotBadge('badge-l2tp-status', (v.active_l2tp || 0) > 0 || v.l2tp_connected);
- setDotBadge('badge-pptp-status', (v.active_pptp || 0) > 0 || v.pptp_connected);
- }
- // Total Live Bandwidth Rate
- let totalRx = 0;
- let totalTx = 0;
- (state.interfaces || []).forEach(i => {
- if (i.rate) {
- totalRx += i.rate.rx_bytes_sec || 0;
- totalTx += i.rate.tx_bytes_sec || 0;
- }
- });
- document.getElementById('stat-traffic-rx').innerText = formatTraffic(totalRx);
- document.getElementById('stat-traffic-tx').innerText = formatTraffic(totalTx);
- }
- function setDotBadge(id, active) {
- const el = document.getElementById(id);
- if (!el) return;
- if (active) {
- el.className = 'w-2 h-2 rounded-full bg-emerald-400 shadow-sm shadow-emerald-400/80';
- } else {
- el.className = 'w-2 h-2 rounded-full bg-slate-600';
- }
- }
- function updateBadges() {
- const bIfaces = document.getElementById('badge-ifaces-count');
- if (bIfaces) bIfaces.innerText = (state.interfaces || []).length;
- const bVlans = document.getElementById('badge-vlans-count');
- if (bVlans) bVlans.innerText = (state.vlans || []).length;
- if (state.fwSummary) {
- const totalFwRules = (state.fwSummary.filter_rules_count || 0) + (state.fwSummary.nat_rules_count || 0) + (state.fwSummary.mangle_rules_count || 0);
- const badgeFw = document.getElementById('badge-firewall-count');
- if (badgeFw) badgeFw.innerText = totalFwRules;
- }
- if (state.vpnStatus) {
- const v = state.vpnStatus;
- const bEoIP = document.getElementById('badge-eoip-count');
- if (bEoIP) bEoIP.innerText = v.total_eoip || 0;
- const bVXLAN = document.getElementById('badge-vxlan-count');
- if (bVXLAN) bVXLAN.innerText = v.total_vxlan || 0;
- const bAero = document.getElementById('badge-aerotun-count');
- if (bAero) bAero.innerText = v.total_aerotun || 0;
- const bPPPSess = document.getElementById('badge-ppp-sessions');
- if (bPPPSess) bPPPSess.innerText = v.total_ppp_sessions || 0;
- setDotBadge('badge-pppoe-status', v.active_pppoe > 0 || v.pppoe_server_running);
- setDotBadge('badge-wg-status', v.active_wireguard > 0);
- setDotBadge('badge-ipsec-status', v.active_ipsec > 0 || v.ipsec_server_running);
- setDotBadge('badge-l2tp-status', v.active_l2tp > 0 || v.l2tp_server_running);
- setDotBadge('badge-pptp-status', v.active_pptp > 0 || v.pptp_server_running);
- }
- if (state.dynSummary) {
- const d = state.dynSummary;
- setDotBadge('badge-bgp-dot', d.bgp_running);
- setDotBadge('badge-ospf-dot', d.ospf_running);
- const bBgp = document.getElementById('badge-bgp-count');
- if (bBgp) bBgp.innerText = (state.bgpPeers || []).length;
- const bOspf = document.getElementById('badge-ospf-count');
- if (bOspf) bOspf.innerText = (state.ospfInterfaces || []).length;
- const bFilters = document.getElementById('badge-filters-count');
- if (bFilters) bFilters.innerText = (state.routingFilters || []).length;
- }
- const bDhcpServer = document.getElementById('badge-dhcp-server-count');
- if (bDhcpServer) {
- bDhcpServer.innerText = state.dhcpServerSummary ? (state.dhcpServerSummary.active_leases || state.dhcpServerSummary.total_servers || 0) : (state.dhcpServers || []).length;
- }
- }
- // Render Dashboard View
- function renderDashboard() {
- const matrix = document.getElementById('port-matrix');
- if (!matrix) return;
- const ifaces = state.interfaces || [];
- const sig = ifaces.map(i => `${i.name}:${i.state}:${(i.ipv4 || []).join(',')}:${i.type}:${i.is_vlan}`).join(';');
- if (matrix.dataset.sig === sig) {
- return; // Structure & link states haven't changed! Do not rebuild or flicker!
- }
- matrix.dataset.sig = sig;
- matrix.innerHTML = '';
- (state.interfaces || []).forEach(iface => {
- const isUp = iface.state === 'UP';
- const isVlan = iface.is_vlan;
- const portCard = document.createElement('div');
- portCard.className = `p-3 rounded-xl border transition-all cursor-pointer select-none group ${
- isUp
- ? (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')
- : 'bg-slate-900/40 border-slate-800/60 opacity-60 hover:opacity-100 hover:border-slate-700'
- }`;
- portCard.onclick = () => openIfaceModal(iface.name);
- let statusPillClass = isUp ? 'bg-emerald-500 shadow-sm shadow-emerald-500/50' : 'bg-rose-500';
- if (isVlan) statusPillClass = isUp ? 'bg-cyan-400 shadow-sm shadow-cyan-400/50' : 'bg-rose-500';
- portCard.innerHTML = `
- <div class="flex items-center justify-between mb-2">
- <span class="font-bold text-xs font-mono text-white group-hover:text-brand-400 transition truncate">${iface.name}</span>
- <span class="w-2 h-2 rounded-full ${statusPillClass}"></span>
- </div>
- <div class="text-[11px] font-mono text-slate-300 truncate">${iface.ipv4 && iface.ipv4.length > 0 ? iface.ipv4[0] : (iface.mac || 'No IP')}</div>
- <div class="mt-2 flex items-center justify-between text-[10px] text-slate-400">
- <span class="uppercase tracking-wider font-semibold">${isVlan ? `VLAN ${iface.vlan_id}` : iface.type}</span>
- <span id="port-card-rate-${iface.name}">${iface.rate?.rx_human || '0 B/s'}</span>
- </div>
- `;
- matrix.appendChild(portCard);
- });
- const ifaceTbody = document.getElementById('quick-interfaces-table');
- if (ifaceTbody) {
- ifaceTbody.innerHTML = '';
- (state.interfaces || []).forEach(i => {
- const isUp = i.state === 'UP';
- const tr = document.createElement('tr');
- tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
- tr.onclick = () => openIfaceModal(i.name);
- const rxStr = i.rate?.rx_human || '0 B/s';
- const txStr = i.rate?.tx_human || '0 B/s';
- tr.innerHTML = `
- <td class="py-2.5 font-bold text-white flex items-center gap-2">
- <span class="w-2 h-2 rounded-full ${isUp ? 'bg-emerald-400 shadow-sm shadow-emerald-400/50' : 'bg-rose-400'}"></span>
- <span>${i.name}</span>
- </td>
- <td class="py-2.5 text-slate-300 font-sans">
- ${getRoleBadge(i.role || 'LAN')}
- </td>
- <td class="py-2.5 text-slate-400 text-[11px] font-mono">${i.mac || '-'}</td>
- <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>
- <td class="py-2.5 text-slate-300 text-[11px] font-mono">
- <span id="quick-rx-${i.name}" class="text-emerald-400">↓ ${rxStr}</span> <span class="text-slate-600">•</span> <span id="quick-tx-${i.name}" class="text-cyan-400">↑ ${txStr}</span>
- </td>
- <td class="py-2.5 text-right font-sans font-semibold">
- <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>
- </td>
- `;
- ifaceTbody.appendChild(tr);
- });
- }
- const vlanTbody = document.getElementById('quick-vlans-table');
- if (vlanTbody) {
- vlanTbody.innerHTML = '';
- }
- }
- // Expand / Collapse Handlers
- function toggleExpand(parentName) {
- if (state.expandedParents.has(parentName)) {
- state.expandedParents.delete(parentName);
- } else {
- state.expandedParents.add(parentName);
- }
- renderInterfacesList();
- }
- // VLAN Support Checker: 802.1Q sub-interfaces are only supported on physical ethernet, veth, bridge, bond
- function supportsVLAN(iface) {
- if (!iface) return false;
- if (iface.is_vlan) return false;
- const name = (iface.name || '').toLowerCase();
- const type = (iface.type || '').toLowerCase();
- const role = (iface.role || '').toLowerCase();
- // Exclude loopback
- if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
- // Exclude WireGuard (Layer 3 tunnel, no 802.1Q support)
- if (type === 'wireguard' || name.startsWith('wg')) return false;
- // Exclude PPP / PPPoE
- if (type === 'ppp' || name.startsWith('ppp')) return false;
- // Exclude other Layer 3 tunnels and dummy devices
- if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
- name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
- return false;
- }
- // If name already contains a dot, it's already a sub-interface
- if (name.includes('.')) return false;
- return true;
- }
- // DHCP Client Support Checker: Only broadcast-capable layer-2 interfaces (Ethernet, veth, VLAN, bridge, bond)
- function supportsDHCPClient(iface) {
- if (!iface) return false;
- const name = (iface.name || '').toLowerCase();
- const type = (iface.type || '').toLowerCase();
- const role = (iface.role || '').toLowerCase();
- // Exclude loopback
- if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
- // Exclude WireGuard (Layer 3 point-to-point tunnel, no broadcast/DHCP)
- if (type === 'wireguard' || name.startsWith('wg')) return false;
- // Exclude PPP / PPPoE / L2TP / PPTP tunnels
- if (type === 'ppp' || name.startsWith('ppp') || name.startsWith('l2tp') || name.startsWith('pptp')) return false;
- // Exclude other Layer 3 tunnels and dummy devices
- if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
- name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
- return false;
- }
- // Exclude bridge member/slave ports (bridge itself handles IP / DHCP)
- const isBridgePort = (state.bridgePorts || []).some(bp => bp.interface === iface.name);
- if (isBridgePort) return false;
- return true;
- }
- // Expand / Collapse Handlers
- function toggleExpand(parentName) {
- const childVlans = (state.vlans || []).filter(v => v.parent_name === parentName || v.name.startsWith(parentName + '.'));
- if (childVlans.length === 0) {
- // Cannot expand an interface with no VLANs
- state.expandedParents.delete(parentName);
- return;
- }
- if (state.expandedParents.has(parentName)) {
- state.expandedParents.delete(parentName);
- } else {
- state.expandedParents.add(parentName);
- }
- renderInterfacesList();
- }
- function expandAllIfaces(expand) {
- if (expand) {
- (state.interfaces || []).forEach(i => {
- const hasVlans = (state.vlans || []).some(v => v.parent_name === i.name || v.name.startsWith(i.name + '.'));
- if (!i.is_vlan && hasVlans) state.expandedParents.add(i.name);
- });
- } else {
- state.expandedParents.clear();
- }
- renderInterfacesList();
- }
- // =========================================================================
- // INTERFACE ROLE TAGS MANAGEMENT
- // =========================================================================
- const ROLE_COLORS = {
- amber: { bg: 'bg-amber-500/20', text: 'text-amber-300', border: 'border-amber-500/30' },
- blue: { bg: 'bg-blue-500/20', text: 'text-blue-300', border: 'border-blue-500/30' },
- cyan: { bg: 'bg-cyan-500/20', text: 'text-cyan-300', border: 'border-cyan-500/30' },
- emerald: { bg: 'bg-emerald-500/20', text: 'text-emerald-300', border: 'border-emerald-500/30' },
- purple: { bg: 'bg-purple-500/20', text: 'text-purple-300', border: 'border-purple-500/30' },
- rose: { bg: 'bg-rose-500/20', text: 'text-rose-300', border: 'border-rose-500/30' },
- indigo: { bg: 'bg-indigo-500/20', text: 'text-indigo-300', border: 'border-indigo-500/30' },
- sky: { bg: 'bg-sky-500/20', text: 'text-sky-300', border: 'border-sky-500/30' },
- slate: { bg: 'bg-slate-800', text: 'text-slate-300', border: 'border-slate-700' }
- };
- function getRoleBadge(roleName) {
- const name = roleName || 'LAN';
- const role = (state.roles || []).find(r => r.name.toLowerCase() === name.toLowerCase() || r.id.toLowerCase() === name.toLowerCase());
- const colorKey = (role?.color || 'blue').toLowerCase();
- const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
- return `<span class="px-2 py-0.5 rounded text-[10px] font-semibold ${theme.bg} ${theme.text} border ${theme.border}" title="Role Tag: ${escapeHtml(name)}">${escapeHtml(name)}</span>`;
- }
- function switchIfaceSubTab(subTab) {
- state.activeIfaceSubTab = subTab;
- const treeTab = document.getElementById('ifaces-subtab-tree');
- const rolesTab = document.getElementById('ifaces-subtab-roles');
- const btnTree = document.getElementById('ifaces-subtab-btn-tree');
- const btnRoles = document.getElementById('ifaces-subtab-btn-roles');
- if (subTab === 'roles') {
- treeTab?.classList.add('hidden');
- rolesTab?.classList.remove('hidden');
- if (btnRoles) {
- btnRoles.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-brand-500/10 text-brand-400 border border-brand-500/20 transition flex items-center gap-1.5';
- }
- if (btnTree) {
- btnTree.className = 'px-3.5 py-1.5 rounded-lg text-xs font-medium text-slate-400 hover:text-white hover:bg-slate-800 transition flex items-center gap-1.5';
- }
- loadRoles();
- } else {
- rolesTab?.classList.add('hidden');
- treeTab?.classList.remove('hidden');
- if (btnTree) {
- btnTree.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-brand-500/10 text-brand-400 border border-brand-500/20 transition flex items-center gap-1.5';
- }
- if (btnRoles) {
- btnRoles.className = 'px-3.5 py-1.5 rounded-lg text-xs font-medium text-slate-400 hover:text-white hover:bg-slate-800 transition flex items-center gap-1.5';
- }
- renderInterfacesList();
- }
- }
- async function loadRoles() {
- try {
- const res = await fetch(`${API_BASE}/roles`);
- if (res.ok) {
- state.roles = await res.json();
- const countEl = document.getElementById('badge-roles-count');
- if (countEl) countEl.innerText = (state.roles || []).length;
- renderRolesTable();
- populateRoleSelects();
- }
- } catch (err) {
- console.error('Failed to load role tags:', err);
- }
- }
- function renderRolesTable() {
- const tbody = document.getElementById('roles-table-body');
- const empty = document.getElementById('roles-empty-state');
- if (!tbody) return;
- const roles = state.roles || [];
- if (roles.length === 0) {
- tbody.innerHTML = '';
- empty?.classList.remove('hidden');
- return;
- }
- empty?.classList.add('hidden');
- const sig = roles.map(r => `${r.id}:${r.name}:${r.color}:${r.description}:${(r.interfaces||[]).join(',')}`).join(';');
- if (tbody.dataset.sig === sig) return;
- tbody.dataset.sig = sig;
- tbody.innerHTML = roles.map(r => {
- const colorKey = (r.color || 'blue').toLowerCase();
- const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
- const ifaces = Array.isArray(r.interfaces) ? r.interfaces : [];
- const ifacesChips = ifaces.length > 0
- ? ifaces.map(name => `<span onclick="openIfaceModal('${escapeHtml(name)}')" class="cursor-pointer px-2 py-0.5 rounded text-[10px] font-mono bg-slate-800 text-slate-200 border border-slate-700 hover:border-cyan-500 transition mr-1 mb-1 inline-block" title="Click to view/edit ${escapeHtml(name)}">${escapeHtml(name)}</span>`).join('')
- : '<span class="text-slate-600 font-sans text-xs italic">Unassigned (0)</span>';
- return `
- <tr class="hover:bg-slate-800/40 transition">
- <td class="py-3 px-4">
- <span class="px-2.5 py-1 rounded text-xs font-semibold ${theme.bg} ${theme.text} border ${theme.border}">
- ${escapeHtml(r.name)}
- </span>
- </td>
- <td class="py-3 px-4 font-bold text-white font-mono flex items-center gap-2">
- <span>${escapeHtml(r.name)}</span>
- ${r.builtin ? '<span class="text-[9px] px-1.5 py-0.2 rounded bg-slate-800 text-slate-400 border border-slate-700 uppercase font-sans">Builtin</span>' : ''}
- </td>
- <td class="py-3 px-4 font-sans capitalize text-slate-300">
- <span class="inline-flex items-center gap-1.5">
- <span class="w-2 h-2 rounded-full ${theme.bg.replace('/20', '')}"></span>
- <span>${escapeHtml(r.color || 'blue')}</span>
- </span>
- </td>
- <td class="py-3 px-4 font-sans text-slate-400 text-xs">${escapeHtml(r.description || '-')}</td>
- <td class="py-3 px-4 font-sans">
- <div class="flex flex-wrap items-center">
- ${ifacesChips}
- </div>
- </td>
- <td class="py-3 px-4 text-right space-x-2 font-sans whitespace-nowrap">
- <button onclick="openRoleModal('${escapeHtml(r.id)}')"
- class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold px-2 py-1 rounded hover:bg-slate-800 transition">
- Edit
- </button>
- <button onclick="deleteRoleTag('${escapeHtml(r.id)}', '${escapeHtml(r.name)}')"
- class="text-xs text-rose-400 hover:text-rose-300 font-semibold px-2 py-1 rounded hover:bg-slate-800 transition">
- Delete
- </button>
- </td>
- </tr>
- `;
- }).join('');
- }
- function openRoleModal(id = null) {
- const modal = document.getElementById('role-modal');
- if (!modal) return;
- const idInput = document.getElementById('role-modal-id');
- const nameInput = document.getElementById('role-modal-name');
- const colorSelect = document.getElementById('role-modal-color');
- const descInput = document.getElementById('role-modal-desc');
- const title = document.getElementById('role-modal-title');
- if (id) {
- const role = (state.roles || []).find(r => r.id === id);
- if (role) {
- if (title) title.innerText = `Edit Role Tag: ${role.name}`;
- if (idInput) idInput.value = role.id;
- if (nameInput) nameInput.value = role.name;
- if (colorSelect) colorSelect.value = role.color || 'blue';
- if (descInput) descInput.value = role.description || '';
- }
- } else {
- if (title) title.innerText = 'Add Role Tag';
- if (idInput) idInput.value = '';
- if (nameInput) nameInput.value = '';
- if (colorSelect) colorSelect.value = 'blue';
- if (descInput) descInput.value = '';
- }
- updateRoleModalPreview();
- modal.classList.remove('hidden');
- }
- function closeRoleModal() {
- const modal = document.getElementById('role-modal');
- if (modal) modal.classList.add('hidden');
- }
- function updateRoleModalPreview() {
- const name = document.getElementById('role-modal-name')?.value.trim() || 'Preview';
- const colorKey = (document.getElementById('role-modal-color')?.value || 'blue').toLowerCase();
- const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
- const preview = document.getElementById('role-modal-preview');
- if (preview) {
- preview.innerText = name;
- preview.className = `px-2.5 py-1 rounded text-xs font-semibold ${theme.bg} ${theme.text} border ${theme.border}`;
- }
- }
- async function submitSaveRole(e) {
- e.preventDefault();
- const id = document.getElementById('role-modal-id')?.value;
- const name = document.getElementById('role-modal-name')?.value.trim();
- const color = document.getElementById('role-modal-color')?.value;
- const desc = document.getElementById('role-modal-desc')?.value.trim();
- if (!name) return;
- try {
- const payload = { id, name, color, description: desc };
- const method = id ? 'PUT' : 'POST';
- const url = id ? `${API_BASE}/roles/${encodeURIComponent(id)}` : `${API_BASE}/roles`;
- const res = await fetch(url, {
- method,
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(payload)
- });
- if (res.ok) {
- showToast('Role Tag Saved', `Role tag "${name}" saved successfully`, 'success');
- closeRoleModal();
- await loadRoles();
- fetchData(false);
- } else {
- const err = await res.json();
- showToast('Error', err.error || err.message || 'Failed to save role tag', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deleteRoleTag(id, name) {
- if (!confirm(`Are you sure you want to delete role tag "${name}"?\nInterfaces assigned to this role will default to LAN.`)) return;
- try {
- const res = await fetch(`${API_BASE}/roles/${encodeURIComponent(id)}`, {
- method: 'DELETE'
- });
- if (res.ok) {
- showToast('Role Tag Deleted', `Role tag "${name}" removed`, 'success');
- await loadRoles();
- fetchData(false);
- } else {
- const err = await res.json();
- showToast('Error', err.error || err.message || 'Failed to delete role tag', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- function populateRoleSelects(selectedRole = '') {
- const ifaceSelect = document.getElementById('modal-iface-role');
- const vlanSelect = document.getElementById('vlan-role');
- const roles = state.roles || [];
- const optionsHtml = roles.map(r => `<option value="${escapeHtml(r.name)}">${escapeHtml(r.name)}${r.description ? ` (${escapeHtml(r.description)})` : ''}</option>`).join('');
- if (ifaceSelect) {
- const currentVal = selectedRole || ifaceSelect.value || 'LAN';
- if (ifaceSelect.dataset.optionsSig !== optionsHtml) {
- ifaceSelect.innerHTML = optionsHtml;
- ifaceSelect.dataset.optionsSig = optionsHtml;
- }
- if (currentVal) ifaceSelect.value = currentVal;
- }
- if (vlanSelect) {
- const currentVal = selectedRole || vlanSelect.value || 'LAN';
- if (vlanSelect.dataset.optionsSig !== optionsHtml) {
- vlanSelect.innerHTML = optionsHtml;
- vlanSelect.dataset.optionsSig = optionsHtml;
- }
- if (currentVal) vlanSelect.value = currentVal;
- }
- }
- // Filter and Render Hierarchical Interfaces List
- function filterIfaces(filter) {
- state.ifaceFilter = filter || 'all';
- renderInterfacesList();
- }
- function renderInterfacesList() {
- const tbody = document.getElementById('interfaces-tree-tbody');
- const emptyState = document.getElementById('interfaces-empty-state');
- const summary = document.getElementById('ifaces-list-summary');
- const query = (document.getElementById('iface-search')?.value || '').trim().toLowerCase();
- const allIfaces = state.interfaces || [];
- const allVlans = state.vlans || [];
- const parentIfaces = allIfaces.filter(i => !i.is_vlan);
- const filteredParents = parentIfaces.filter(parent => {
- const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
- if (query) {
- const matchName = parent.name.toLowerCase().includes(query);
- const matchIp = (parent.ipv4 || []).some(ip => ip.toLowerCase().includes(query));
- const matchRole = (parent.role || '').toLowerCase().includes(query);
- const matchType = (parent.type || '').toLowerCase().includes(query);
- const matchVlan = childVlans.some(v =>
- v.name.toLowerCase().includes(query) ||
- String(v.vlan_id).includes(query) ||
- (v.ipv4 || []).some(ip => ip.toLowerCase().includes(query)) ||
- (v.description || '').toLowerCase().includes(query)
- );
- if (!matchName && !matchIp && !matchRole && !matchType && !matchVlan) return false;
- }
- if (state.ifaceFilter === 'has_vlans') return childVlans.length > 0;
- if (state.ifaceFilter === 'physical') return parent.type !== 'loopback';
- if (state.ifaceFilter === 'up') return parent.state === 'UP';
- return true;
- });
- if (summary) {
- summary.innerText = `${parentIfaces.length} Interfaces • ${allVlans.length} Active VLANs`;
- }
- if (filteredParents.length === 0) {
- emptyState?.classList.remove('hidden');
- tbody.innerHTML = '';
- return;
- }
- emptyState?.classList.add('hidden');
- const sig = `${state.ifaceFilter}|${query}|` + filteredParents.map(p => {
- const cVlans = allVlans.filter(v => v.parent_name === p.name || v.name.startsWith(p.name + '.'));
- const dhcp = (state.dhcpClients || []).find(dc => dc.interface === p.name);
- return `${p.name}:${p.state}:${p.role||'LAN'}:${(p.ipv4||[]).join(',')}:${p.mtu}:${cVlans.length}:${state.expandedParents.has(p.name)}:${dhcp?.status || ''}`;
- }).join(';');
- if (tbody.dataset.sig === sig) {
- return; // ZERO changes to structure, links, IPs or VLANs! Do not rebuild DOM!
- }
- tbody.dataset.sig = sig;
- tbody.innerHTML = '';
- filteredParents.forEach(parent => {
- const isUp = parent.state === 'UP';
- const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
- const hasVlans = childVlans.length > 0;
- const isExpanded = hasVlans && state.expandedParents.has(parent.name);
- const canHaveVlan = supportsVLAN(parent);
- const parentRow = document.createElement('tr');
- parentRow.className = `hover:bg-slate-800/50 transition border-b border-slate-800/80 ${isExpanded ? 'bg-slate-900/80' : ''}`;
- parentRow.innerHTML = `
- <td class="py-3 px-3 text-center">
- ${hasVlans ? `
- <button onclick="toggleExpand('${parent.name}')" title="${isExpanded ? 'Collapse VLANs' : 'Expand VLANs'}"
- class="w-6 h-6 rounded flex items-center justify-center hover:bg-slate-800 text-slate-400 hover:text-white transition">
- <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">
- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M9 5l7 7-7 7" />
- </svg>
- </button>
- ` : `
- <div class="w-6 h-6 flex items-center justify-center text-slate-700 select-none">
- <span class="w-1.5 h-1.5 rounded-full bg-slate-800"></span>
- </div>
- `}
- </td>
- <td class="py-3 px-4">
- <div class="flex items-center space-x-2.5">
- <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">
- ${parent.type === 'loopback' ? 'LO' : (parent.type === 'wireguard' ? 'WG' : (parent.type === 'bridge' ? 'BR' : 'NIC'))}
- </div>
- <div>
- <div class="flex items-center gap-2">
- <span class="font-bold text-white text-sm cursor-pointer hover:text-cyan-400 flex items-center gap-1.5" onclick="${hasVlans ? `toggleExpand('${parent.name}')` : `openIfaceModal('${parent.name}')`}" title="${hasVlans ? 'Click to expand VLANs, or click pencil to rename' : 'Click to configure or rename interface'}">
- <span>${parent.name}</span>
- <svg onclick="event.stopPropagation(); openIfaceModal('${parent.name}')" class="w-3.5 h-3.5 text-slate-500 hover:text-cyan-400 opacity-60 hover:opacity-100 cursor-pointer" title="Configure / Rename ${parent.name}" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
- </span>
- ${hasVlans ? `
- <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>
- ` : `
- <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>
- `}
- </div>
- <div class="text-[10px] text-slate-500 font-sans mt-0.5">${parent.type}</div>
- </div>
- </div>
- </td>
- <td class="py-3 px-4 font-sans">
- <div class="flex items-center gap-1.5">
- ${getRoleBadge(parent.role || 'LAN')}
- <span class="text-xs text-slate-400 truncate max-w-[120px]">${parent.description || '-'}</span>
- </div>
- </td>
- <td class="py-3 px-4">
- ${parent.ipv4 && parent.ipv4.length > 0
- ? `<div class="text-white font-medium">${parent.ipv4[0]}</div>`
- : '<span class="text-slate-600 font-sans">Unassigned</span>'
- }
- ${(() => {
- const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
- if (!c) return '';
- 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');
- 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>`;
- })()}
- </td>
- <td class="py-3 px-4 text-slate-400 text-[11px]">
- <div>${parent.mac || 'N/A'}</div>
- <div class="text-[10px] text-slate-500">MTU ${parent.mtu}</div>
- </td>
- <td class="py-3 px-4 text-[11px]">
- <div class="flex items-center space-x-2">
- <span id="iface-rate-rx-${parent.name}" class="text-emerald-400">↓ ${parent.rate?.rx_human || '0 B/s'}</span>
- <span id="iface-rate-tx-${parent.name}" class="text-cyan-400">↑ ${parent.rate?.tx_human || '0 B/s'}</span>
- </div>
- </td>
- <td class="py-3 px-4 font-sans">
- <button onclick="toggleInterfaceState('${parent.name}', '${isUp ? 'down' : 'up'}')"
- class="flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full transition ${
- 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'
- }" title="Click to toggle link status">
- <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
- <span>${parent.state}</span>
- </button>
- </td>
- <td class="py-3 px-4 text-right space-x-2 font-sans">
- ${(() => {
- const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
- if (c) {
- 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>`;
- }
- if (!supportsDHCPClient(parent)) {
- return '';
- }
- 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>`;
- })()}
- ${canHaveVlan ? `
- <button onclick="openVlanModal('${parent.name}')"
- 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">
- + Add VLAN
- </button>
- ` : ''}
- <button onclick="openIfaceModal('${parent.name}')"
- 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">
- Edit
- </button>
- </td>
- `;
- tbody.appendChild(parentRow);
- if (isExpanded) {
- const drawerRow = document.createElement('tr');
- drawerRow.className = 'bg-slate-950/80 border-b border-slate-800/90';
- const drawerCell = document.createElement('td');
- drawerCell.colSpan = 8;
- drawerCell.className = 'p-0';
- drawerCell.innerHTML = `
- <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">
- <div class="flex items-center justify-between mb-3">
- <div class="flex items-center space-x-3">
- <span class="font-bold text-xs text-white uppercase tracking-wider flex items-center gap-1.5 font-sans">
- <span>VLAN Sub-interfaces on <code class="text-cyan-300 lowercase">${parent.name}</code></span>
- </span>
- <span class="text-[11px] bg-cyan-950 text-cyan-400 px-2 py-0.5 rounded-full border border-cyan-800/60 font-mono">
- ${childVlans.length} Attached
- </span>
- </div>
- <button onclick="openVlanModal('${parent.name}')"
- 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">
- <span>+ Create VLAN on ${parent.name}</span>
- </button>
- </div>
- ${childVlans.length === 0 ? `
- <div class="p-6 text-center border border-dashed border-slate-800 rounded-xl bg-slate-900/40 font-sans">
- <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>
- <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">
- <span>+ Create Your First VLAN on ${parent.name}</span>
- </button>
- </div>
- ` : `
- <div class="overflow-x-auto rounded-lg border border-slate-800 bg-slate-900/90 shadow-inner">
- <table class="w-full text-left text-xs font-mono">
- <thead class="text-slate-400 bg-slate-950/70 border-b border-slate-800 uppercase tracking-wider text-[10px] font-sans">
- <tr>
- <th class="py-2.5 px-4">VLAN ID</th>
- <th class="py-2.5 px-4">Interface Device</th>
- <th class="py-2.5 px-4">Subnet Gateway</th>
- <th class="py-2.5 px-4">Role / Alias</th>
- <th class="py-2.5 px-4">MTU</th>
- <th class="py-2.5 px-4">Throughput</th>
- <th class="py-2.5 px-4">Status</th>
- <th class="py-2.5 px-4 text-right">Actions</th>
- </tr>
- </thead>
- <tbody class="divide-y divide-slate-800/70">
- ${childVlans.map(v => {
- const isVlanUp = v.state === 'UP';
- return `
- <tr class="hover:bg-slate-800/40 transition">
- <td class="py-2.5 px-4">
- <span class="px-2 py-0.5 rounded text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800 shadow-sm">
- VLAN ${v.vlan_id}
- </span>
- </td>
- <td class="py-2.5 px-4 font-bold text-white flex items-center gap-1.5">
- <span class="text-cyan-500">└─</span>
- <span class="cursor-pointer hover:text-cyan-400 flex items-center gap-1" onclick="openIfaceModal('${v.name}')" title="Configure / Rename ${v.name}">
- <span>${v.name}</span>
- <svg class="w-3 h-3 text-slate-500 hover:text-cyan-400 opacity-60 hover:opacity-100" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
- </span>
- </td>
- <td class="py-2.5 px-4 text-emerald-400 font-medium">
- ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
- ${(() => {
- const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
- if (!c) return '';
- 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';
- 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>`;
- })()}
- </td>
- <td class="py-2.5 px-4 font-sans text-slate-300">
- <div class="flex items-center gap-1.5">
- ${getRoleBadge(v.role || 'LAN')}
- <span class="text-slate-400 text-xs">${v.description || '-'}</span>
- </div>
- </td>
- <td class="py-2.5 px-4 text-slate-400">${v.mtu}</td>
- <td class="py-2.5 px-4 text-[11px]">
- <span id="vlan-rate-rx-${v.name}" class="text-emerald-400">↓ ${v.rate?.rx_human || '0 B/s'}</span>
- <span id="vlan-rate-tx-${v.name}" class="text-cyan-400 ml-1.5">↑ ${v.rate?.tx_human || '0 B/s'}</span>
- </td>
- <td class="py-2.5 px-4 font-sans">
- <button onclick="toggleInterfaceState('${v.name}', '${isVlanUp ? 'down' : 'up'}')"
- class="flex items-center gap-1 text-[11px] font-semibold px-2 py-0.5 rounded-full ${
- 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'
- }">
- <span class="w-1.5 h-1.5 rounded-full ${isVlanUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
- <span>${v.state}</span>
- </button>
- </td>
- <td class="py-2.5 px-4 text-right space-x-1.5 font-sans">
- ${(() => {
- const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
- if (c) {
- 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>`;
- }
- if (!supportsDHCPClient(v)) {
- return '';
- }
- 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>`;
- })()}
- <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>
- <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>
- </td>
- </tr>
- `;
- }).join('')}
- </tbody>
- </table>
- </div>
- `}
- </div>
- `;
- drawerRow.appendChild(drawerCell);
- tbody.appendChild(drawerRow);
- }
- });
- }
- // Render VLANs Dedicated View
- function renderVlansList() {
- const tbody = document.getElementById('vlans-table-body');
- if (!tbody) return;
- const emptyState = document.getElementById('vlans-empty-state');
- const countBadge = document.getElementById('vlans-table-count');
- const query = (document.getElementById('vlan-search')?.value || '').toLowerCase();
- const allVlans = state.vlans || [];
- if (countBadge) countBadge.innerText = allVlans.length;
- const filtered = allVlans.filter(v => {
- if (!query) return true;
- return v.name.toLowerCase().includes(query) ||
- String(v.vlan_id).includes(query) ||
- (v.description || '').toLowerCase().includes(query) ||
- (v.ipv4 && v.ipv4.some(ip => ip.includes(query)));
- });
- if (allVlans.length === 0) {
- emptyState.classList.remove('hidden');
- tbody.innerHTML = '';
- return;
- }
- emptyState.classList.add('hidden');
- const sig = `${query}|` + filtered.map(v => `${v.name}:${v.state}:${(v.ipv4||[]).join(',')}:${v.vlan_id}:${v.mtu}`).join(';');
- if (tbody.dataset.sig === sig) return;
- tbody.dataset.sig = sig;
- tbody.innerHTML = '';
- filtered.forEach(v => {
- const isUp = v.state === 'UP';
- const tr = document.createElement('tr');
- tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
- tr.innerHTML = `
- <td class="py-3 px-4">
- <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">
- VLAN ${v.vlan_id}
- </span>
- </td>
- <td class="py-3 px-4 font-bold text-white">
- <span class="cursor-pointer hover:text-cyan-400 flex items-center gap-1.5" onclick="openIfaceModal('${v.name}')" title="Configure / Rename ${v.name}">
- <span>${v.name}</span>
- <svg class="w-3.5 h-3.5 text-slate-500 hover:text-cyan-400 opacity-60 hover:opacity-100" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
- </span>
- </td>
- <td class="py-3 px-4 text-slate-300">
- <span class="bg-slate-800 text-slate-200 px-2 py-0.5 rounded text-[11px]">${v.parent_name || 'eth0'}</span>
- </td>
- <td class="py-3 px-4 text-emerald-400 font-medium">
- ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
- </td>
- <td class="py-3 px-4 text-slate-300 font-sans">
- <span class="text-slate-400 text-xs">${v.description || v.role || '-'}</span>
- </td>
- <td class="py-3 px-4 text-slate-400">${v.mtu}</td>
- <td class="py-3 px-4 font-sans">
- <button onclick="toggleInterfaceState('${v.name}', '${isUp ? 'down' : 'up'}')"
- class="flex items-center gap-1.5 text-xs font-semibold px-2 py-0.5 rounded-full ${
- 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'
- }">
- <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
- <span>${v.state}</span>
- </button>
- </td>
- <td class="py-3 px-4 text-right space-x-2 font-sans">
- <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>
- <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>
- </td>
- `;
- tbody.appendChild(tr);
- });
- }
- // Toggle interface UP / DOWN
- async function toggleInterfaceState(name, newState) {
- try {
- const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(name)}/state`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ state: newState })
- });
- const data = await res.json();
- if (res.ok) {
- showToast('Interface Updated', `Interface ${name} is now ${newState.toUpperCase()}`, 'success');
- fetchData(false);
- } else {
- showToast('Error', data.message || 'Failed to toggle interface state', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // ---------------- MikroTik Flag & Utilities ----------------
- function renderMikroTikFlag(running, disabled) {
- if (running) {
- 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>`;
- }
- if (disabled) {
- 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>`;
- }
- 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>`;
- }
- function copyToClipboard(text, label = 'Text') {
- navigator.clipboard.writeText(text).then(() => {
- showToast('Copied', `${label} copied to clipboard`, 'success');
- }).catch(() => {
- prompt('Copy value:', text);
- });
- }
- // ======================== PPP Profiles Shared Helper ========================
- async function fetchPPPProfilesList() {
- try {
- const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
- if (res.ok) {
- state.pppProfiles = await res.json();
- }
- } catch (err) {
- console.error('Failed to load PPP profiles:', err);
- }
- }
- function populateProfileSelect(selectId, selectedVal, defaultVal = 'default') {
- const sel = document.getElementById(selectId);
- if (!sel) return;
- const profiles = (state.pppProfiles && state.pppProfiles.length > 0) ? state.pppProfiles : [
- { name: 'default', use_encryption: 'no' },
- { name: 'default-encryption', use_encryption: 'required' }
- ];
- sel.innerHTML = '';
- profiles.forEach(p => {
- const opt = document.createElement('option');
- opt.value = p.name;
- const encBadge = p.use_encryption === 'required' ? ' (MPPE-128)' : (p.use_encryption === 'yes' ? ' (MPPE)' : '');
- opt.innerText = `${p.name}${encBadge}`;
- sel.appendChild(opt);
- });
- if (selectedVal) {
- sel.value = selectedVal;
- } else {
- sel.value = defaultVal;
- }
- if (!sel.value && sel.options.length > 0) {
- sel.selectedIndex = 0;
- }
- }
- // ======================== PPPoE Multi-Instance ========================
- async function loadPPPoE(populateInputs = true) {
- try {
- if (!state.pppProfiles || state.pppProfiles.length === 0) {
- await fetchPPPProfilesList();
- }
- const res = await fetch(`${API_BASE}/vpn/pppoe/clients`);
- const list = await res.json();
- state.pppoeList = Array.isArray(list) ? list : [];
- const badge = document.getElementById('pppoe-count-badge');
- if (badge) badge.innerText = `${state.pppoeList.length} Interface${state.pppoeList.length !== 1 ? 's' : ''}`;
- const tbody = document.getElementById('pppoe-table-body');
- const empty = document.getElementById('pppoe-empty');
- if (!tbody) return;
- tbody.innerHTML = '';
- if (state.pppoeList.length === 0) {
- if (empty) empty.classList.remove('hidden');
- } else {
- if (empty) empty.classList.add('hidden');
- state.pppoeList.forEach(inst => {
- const tr = document.createElement('tr');
- tr.className = 'hover:bg-slate-800/40 transition text-xs';
- tr.innerHTML = `
- <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
- <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
- <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.interface)}</td>
- <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
- <td class="py-2.5 px-3 font-mono text-cyan-300"><span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 border border-slate-700">${escapeHtml(inst.profile || 'default')}</span></td>
- <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${escapeHtml(inst.assigned_ip || '-')}</td>
- <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
- <td class="py-2.5 px-3 text-center">
- <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'}">
- ${inst.default_route ? 'Yes' : 'No'}
- </span>
- </td>
- <td class="py-2.5 px-3 text-right space-x-2 font-sans">
- ${inst.running ? `
- <button onclick="disconnectPPPoEInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
- ` : `
- <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>
- `}
- <button onclick="togglePPPoEState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
- ${inst.disabled ? 'Enable' : 'Disable'}
- </button>
- <button onclick="openEditPPPoEModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
- <button onclick="deletePPPoEInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
- </td>
- `;
- tbody.appendChild(tr);
- });
- }
- } catch (err) {
- console.error('Failed to load PPPoE:', err);
- }
- }
- function openAddPPPoEModal() {
- document.getElementById('pppoe-modal-title').innerText = 'Add PPPoE Client Interface';
- document.getElementById('pppoe-modal-edit-orig').value = '';
- document.getElementById('pppoe-modal-name').value = `pppoe-out${(state.pppoeList || []).length + 1}`;
- document.getElementById('pppoe-modal-name').readOnly = false;
- document.getElementById('pppoe-modal-user').value = '';
- document.getElementById('pppoe-modal-pass').value = '';
- document.getElementById('pppoe-modal-service').value = '';
- document.getElementById('pppoe-modal-mtu').value = '1492';
- document.getElementById('pppoe-modal-defroute').checked = true;
- document.getElementById('pppoe-modal-reconnect').checked = true;
- document.getElementById('pppoe-modal-disabled').checked = false;
- // Populate profiles
- populateProfileSelect('pppoe-modal-profile', 'default', 'default');
- // Populate interfaces
- const sel = document.getElementById('pppoe-modal-iface');
- sel.innerHTML = '';
- (state.interfaces || []).forEach(i => {
- if (i.name === 'lo') return;
- const opt = document.createElement('option');
- opt.value = i.name;
- opt.innerText = `${i.name} (${i.role || i.type})`;
- sel.appendChild(opt);
- });
- document.getElementById('pppoe-modal').classList.remove('hidden');
- }
- function openEditPPPoEModal(name) {
- const inst = (state.pppoeList || []).find(i => i.name === name);
- if (!inst) return;
- document.getElementById('pppoe-modal-title').innerText = `Edit PPPoE Client: ${name}`;
- document.getElementById('pppoe-modal-edit-orig').value = name;
- document.getElementById('pppoe-modal-name').value = inst.name;
- document.getElementById('pppoe-modal-name').readOnly = true;
- document.getElementById('pppoe-modal-user').value = inst.username || '';
- document.getElementById('pppoe-modal-pass').value = inst.password || '';
- document.getElementById('pppoe-modal-service').value = inst.service_name || '';
- document.getElementById('pppoe-modal-mtu').value = inst.mtu || 1492;
- document.getElementById('pppoe-modal-defroute').checked = inst.default_route ?? true;
- document.getElementById('pppoe-modal-reconnect').checked = inst.auto_reconnect ?? true;
- document.getElementById('pppoe-modal-disabled').checked = !!inst.disabled;
- // Populate profiles
- populateProfileSelect('pppoe-modal-profile', inst.profile || 'default', 'default');
- const sel = document.getElementById('pppoe-modal-iface');
- sel.innerHTML = '';
- (state.interfaces || []).forEach(i => {
- if (i.name === 'lo') return;
- const opt = document.createElement('option');
- opt.value = i.name;
- opt.innerText = `${i.name} (${i.role || i.type})`;
- if (i.name === inst.interface) opt.selected = true;
- sel.appendChild(opt);
- });
- document.getElementById('pppoe-modal').classList.remove('hidden');
- }
- function closePPPoEModal() {
- document.getElementById('pppoe-modal').classList.add('hidden');
- }
- async function submitSavePPPoE(e) {
- e.preventDefault();
- const name = document.getElementById('pppoe-modal-name').value.trim();
- const iface = document.getElementById('pppoe-modal-iface').value;
- const user = document.getElementById('pppoe-modal-user').value.trim();
- const pass = document.getElementById('pppoe-modal-pass').value;
- const profile = document.getElementById('pppoe-modal-profile')?.value || 'default';
- const service = document.getElementById('pppoe-modal-service').value.trim();
- const mtu = parseInt(document.getElementById('pppoe-modal-mtu').value, 10) || 1492;
- const defRoute = document.getElementById('pppoe-modal-defroute').checked;
- const reconnect = document.getElementById('pppoe-modal-reconnect').checked;
- const disabled = document.getElementById('pppoe-modal-disabled').checked;
- try {
- const res = await fetch(`${API_BASE}/vpn/pppoe/clients`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- name,
- interface: iface,
- username: user,
- password: pass,
- profile: profile,
- service_name: service,
- mtu,
- default_route: defRoute,
- auto_reconnect: reconnect,
- disabled
- })
- });
- if (res.ok) {
- showToast('PPPoE Saved', `Configuration for ${name} saved`, 'success');
- closePPPoEModal();
- loadPPPoE(false);
- fetchData(false);
- } else {
- const err = await res.json();
- showToast('Error', err.message || 'Failed to save PPPoE', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function connectPPPoEInstance(name) {
- try {
- const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
- if (res.ok) {
- showToast('Connecting', `Dialing ${name}...`, 'info');
- setTimeout(() => loadPPPoE(false), 2000);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function disconnectPPPoEInstance(name) {
- try {
- const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
- if (res.ok) {
- showToast('Disconnected', `${name} session terminated`, 'info');
- setTimeout(() => loadPPPoE(false), 1000);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function togglePPPoEState(name, enable) {
- try {
- const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/state`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ enabled: enable })
- });
- if (res.ok) {
- showToast(enable ? 'Enabled' : 'Disabled', `${name} is now ${enable ? 'enabled' : 'disabled'}`, 'info');
- loadPPPoE(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deletePPPoEInstance(name) {
- if (!confirm(`Are you sure you want to delete PPPoE client ${name}?`)) return;
- try {
- const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
- if (res.ok) {
- showToast('Deleted', `PPPoE client ${name} removed`, 'success');
- loadPPPoE(false);
- fetchData(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // ======================== WireGuard Multi-Interface & Multi-Peer ========================
- state.wgSubTab = 'ifaces';
- function switchWGSubTab(tab) {
- state.wgSubTab = tab;
- const ifacesPanel = document.getElementById('wg-subtab-ifaces');
- const peersPanel = document.getElementById('wg-subtab-peers');
- const ifacesBtn = document.getElementById('wg-subtab-btn-ifaces');
- const peersBtn = document.getElementById('wg-subtab-btn-peers');
- if (tab === 'ifaces') {
- ifacesPanel?.classList.remove('hidden');
- peersPanel?.classList.add('hidden');
- 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';
- 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';
- } else {
- ifacesPanel?.classList.add('hidden');
- peersPanel?.classList.remove('hidden');
- 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';
- 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';
- renderWGPeers();
- }
- }
- async function loadWireGuard(populateInputs = true) {
- try {
- const [ifacesRes, peersRes] = await Promise.all([
- fetch(`${API_BASE}/vpn/wireguard/interfaces`),
- fetch(`${API_BASE}/vpn/wireguard/peers`)
- ]);
- const ifaces = ifacesRes.ok ? await ifacesRes.json() : [];
- const peers = peersRes.ok ? await peersRes.json() : [];
- state.wgInterfaces = Array.isArray(ifaces) ? ifaces : [];
- state.wgPeers = Array.isArray(peers) ? peers : [];
- // Badges
- const ifacesCountBadge = document.getElementById('wg-ifaces-count');
- if (ifacesCountBadge) ifacesCountBadge.innerText = `${state.wgInterfaces.length} Interfaces`;
- const peersCountBadge = document.getElementById('wg-peers-count');
- if (peersCountBadge) peersCountBadge.innerText = `${state.wgPeers.length} Peers`;
- const subTabIfaces = document.getElementById('wg-subtab-badge-ifaces');
- if (subTabIfaces) subTabIfaces.innerText = state.wgInterfaces.length;
- const subTabPeers = document.getElementById('wg-subtab-badge-peers');
- if (subTabPeers) subTabPeers.innerText = state.wgPeers.length;
- // Render Interfaces
- const ifacesTbody = document.getElementById('wg-ifaces-table-body');
- const ifacesEmpty = document.getElementById('wg-ifaces-empty');
- if (ifacesTbody) {
- ifacesTbody.innerHTML = '';
- if (state.wgInterfaces.length === 0) {
- if (ifacesEmpty) ifacesEmpty.classList.remove('hidden');
- } else {
- if (ifacesEmpty) ifacesEmpty.classList.add('hidden');
- state.wgInterfaces.forEach(iface => {
- const peersOnIface = state.wgPeers.filter(p => p.interface === iface.name).length;
- const tr = document.createElement('tr');
- tr.className = 'hover:bg-slate-800/40 transition text-xs';
- tr.innerHTML = `
- <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(iface.running, iface.disabled)}</td>
- <td class="py-2.5 px-3">
- <div class="flex items-center gap-1.5">
- <span class="font-bold text-white">${escapeHtml(iface.name)}</span>
- ${iface.comment ? `<span class="text-[10px] text-slate-400 font-sans italic">(${escapeHtml(iface.comment)})</span>` : ''}
- </div>
- </td>
- <td class="py-2.5 px-3 text-amber-400 font-mono">${iface.listen_port}</td>
- <td class="py-2.5 px-3 text-emerald-400 font-mono">${iface.address || '<span class="text-slate-600 font-sans">--</span>'}</td>
- <td class="py-2.5 px-3 text-slate-300 font-mono">
- <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${iface.public_key}', 'Public Key')" title="Click to copy: ${iface.public_key}">
- ${(iface.public_key || '').substring(0, 10)}... 📋
- </span>
- </td>
- <td class="py-2.5 px-3 text-slate-400 font-mono">${iface.mtu || 1420}</td>
- <td class="py-2.5 px-3 text-center">
- <span class="px-2 py-0.5 rounded text-[10px] font-sans bg-slate-800 text-slate-300">${peersOnIface} peer${peersOnIface !== 1 ? 's' : ''}</span>
- </td>
- <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
- ${iface.running ? `
- <button onclick="stopWGInterface('${iface.name}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Stop</button>
- ` : `
- <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>
- `}
- <button onclick="toggleWGInterfaceState('${iface.name}', ${iface.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white font-medium">
- ${iface.disabled ? 'Enable' : 'Disable'}
- </button>
- <button onclick="openEditWGInterfaceModal('${iface.name}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
- <button onclick="deleteWGInterface('${iface.name}')" class="text-xs text-slate-500 hover:text-rose-400 font-medium">Delete</button>
- </td>
- `;
- ifacesTbody.appendChild(tr);
- });
- }
- }
- // Populate filter dropdown in peers tab
- const filterSel = document.getElementById('wg-peers-filter-iface');
- if (filterSel) {
- const currentVal = filterSel.value;
- filterSel.innerHTML = '<option value="">All Interfaces</option>';
- state.wgInterfaces.forEach(i => {
- const opt = document.createElement('option');
- opt.value = i.name;
- opt.innerText = i.name;
- if (i.name === currentVal) opt.selected = true;
- filterSel.appendChild(opt);
- });
- }
- renderWGPeers();
- } catch (err) {
- console.error('Failed to load WireGuard:', err);
- }
- }
- function formatWGPeerEndpoint(address, port) {
- if (!address || address === '(none)') return '--';
- let addr = address.trim();
- let p = port || 0;
- while (addr.includes(':') && !addr.startsWith('[')) {
- const lastColon = addr.lastIndexOf(':');
- const maybePort = addr.substring(lastColon + 1);
- if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
- if (!p) p = parseInt(maybePort, 10);
- addr = addr.substring(0, lastColon);
- } else {
- break;
- }
- }
- return p ? `${addr}:${p}` : addr;
- }
- function renderWGPeers() {
- const filterSel = document.getElementById('wg-peers-filter-iface');
- const selectedIface = filterSel ? filterSel.value : '';
- const tbody = document.getElementById('wg-peers-table-body');
- const empty = document.getElementById('wg-peers-empty');
- if (!tbody) return;
- tbody.innerHTML = '';
- const filtered = selectedIface ? state.wgPeers.filter(p => p.interface === selectedIface) : state.wgPeers;
- if (filtered.length === 0) {
- if (empty) empty.classList.remove('hidden');
- } else {
- if (empty) empty.classList.add('hidden');
- filtered.forEach(p => {
- const isOnline = p.latest_handshake && !p.latest_handshake.includes('Never');
- const tr = document.createElement('tr');
- tr.className = 'hover:bg-slate-800/40 transition text-xs';
- tr.innerHTML = `
- <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isOnline, p.disabled)}</td>
- <td class="py-2.5 px-3 font-mono font-bold text-rose-400">${escapeHtml(p.interface)}</td>
- <td class="py-2.5 px-3 font-bold text-white font-sans">${escapeHtml(p.name || 'Unnamed')}</td>
- <td class="py-2.5 px-3 text-slate-300 font-mono">
- <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${p.public_key}', 'Peer Public Key')" title="${p.public_key}">
- ${(p.public_key || '').substring(0, 10)}... 📋
- </span>
- </td>
- <td class="py-2.5 px-3 text-emerald-400 font-mono font-semibold">${(p.allowed_ips || []).join(', ')}</td>
- <td class="py-2.5 px-3 text-slate-400 font-mono">${formatWGPeerEndpoint(p.endpoint_address, p.endpoint_port)}</td>
- <td class="py-2.5 px-3 text-slate-300 font-sans">${p.latest_handshake || 'Never'}</td>
- <td class="py-2.5 px-3 font-mono text-[11px]">
- <span class="text-emerald-400">↓ ${p.transfer_rx_human || '0 B'}</span>
- <span class="text-cyan-400 ml-1">↑ ${p.transfer_tx_human || '0 B'}</span>
- </td>
- <td class="py-2.5 px-3 text-right font-sans space-x-2 whitespace-nowrap">
- <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">
- ${p.disabled ? 'Enable' : 'Disable'}
- </button>
- <button onclick="openEditWGPeerModal('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
- <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>
- <button onclick="deleteWGPeer('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Delete</button>
- </td>
- `;
- tbody.appendChild(tr);
- });
- }
- }
- function openAddWGInterfaceModal() {
- document.getElementById('wg-iface-modal-title').innerText = 'Add WireGuard Interface';
- document.getElementById('wg-iface-modal-edit-orig').value = '';
- const nameEl = document.getElementById('wg-iface-modal-name');
- nameEl.value = `wg${(state.wgInterfaces || []).length}`;
- nameEl.readOnly = false;
- document.getElementById('wg-iface-modal-port').value = 51820 + (state.wgInterfaces || []).length;
- document.getElementById('wg-iface-modal-addr').value = `10.${10 + (state.wgInterfaces || []).length}.0.1/24`;
- document.getElementById('wg-iface-modal-mtu').value = '1420';
- document.getElementById('wg-iface-modal-comment').value = '';
- document.getElementById('wg-iface-modal-pubkey').value = '';
- document.getElementById('wg-iface-modal-privkey').value = '';
- document.getElementById('wg-iface-modal-disabled').checked = false;
- generateWGInterfaceKeys();
- document.getElementById('wg-iface-modal').classList.remove('hidden');
- }
- function openEditWGInterfaceModal(name) {
- const iface = (state.wgInterfaces || []).find(i => i.name === name);
- if (!iface) return;
- document.getElementById('wg-iface-modal-title').innerText = `Edit WireGuard Interface: ${name}`;
- document.getElementById('wg-iface-modal-edit-orig').value = name;
- const nameEl = document.getElementById('wg-iface-modal-name');
- nameEl.value = iface.name;
- nameEl.readOnly = false; // ALLOW RENAMING
- document.getElementById('wg-iface-modal-port').value = iface.listen_port || 51820;
- document.getElementById('wg-iface-modal-addr').value = iface.address || '';
- document.getElementById('wg-iface-modal-mtu').value = iface.mtu || 1420;
- document.getElementById('wg-iface-modal-comment').value = iface.comment || '';
- document.getElementById('wg-iface-modal-pubkey').value = iface.public_key || '';
- document.getElementById('wg-iface-modal-privkey').value = iface.private_key || '';
- document.getElementById('wg-iface-modal-disabled').checked = !!iface.disabled;
- document.getElementById('wg-iface-modal').classList.remove('hidden');
- }
- function closeAddWGInterfaceModal() {
- document.getElementById('wg-iface-modal').classList.add('hidden');
- }
- async function generateWGInterfaceKeys() {
- try {
- const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
- const keys = await res.json();
- if (res.ok) {
- document.getElementById('wg-iface-modal-privkey').value = keys.private_key;
- document.getElementById('wg-iface-modal-pubkey').value = keys.public_key;
- }
- } catch (err) {
- showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
- }
- }
- async function onWGInterfacePrivKeyInput() {
- const privKey = document.getElementById('wg-iface-modal-privkey').value.trim();
- if (!privKey) return;
- try {
- const res = await fetch(`${API_BASE}/vpn/wireguard/calc-pubkey`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ private_key: privKey })
- });
- if (res.ok) {
- const data = await res.json();
- if (data.public_key) {
- document.getElementById('wg-iface-modal-pubkey').value = data.public_key;
- }
- }
- } catch (err) {
- // Ignore while typing
- }
- }
- function toggleWGPrivKeyVisibility() {
- const el = document.getElementById('wg-iface-modal-privkey');
- const btn = document.getElementById('btn-toggle-wg-privkey');
- if (el.type === 'password') {
- el.type = 'text';
- btn.innerText = '🙈 Hide';
- } else {
- el.type = 'password';
- btn.innerText = '👁️ Show';
- }
- }
- function copyWGInterfacePubKey() {
- const pub = document.getElementById('wg-iface-modal-pubkey').value;
- if (pub) copyToClipboard(pub, 'Interface Public Key');
- }
- async function submitSaveWGInterface(e) {
- e.preventDefault();
- const origName = document.getElementById('wg-iface-modal-edit-orig').value.trim();
- const name = document.getElementById('wg-iface-modal-name').value.trim();
- const port = parseInt(document.getElementById('wg-iface-modal-port').value, 10) || 51820;
- const addr = document.getElementById('wg-iface-modal-addr').value.trim();
- const mtu = parseInt(document.getElementById('wg-iface-modal-mtu').value, 10) || 1420;
- const comment = document.getElementById('wg-iface-modal-comment').value.trim();
- const pub = document.getElementById('wg-iface-modal-pubkey').value.trim();
- const priv = document.getElementById('wg-iface-modal-privkey').value.trim();
- const disabled = document.getElementById('wg-iface-modal-disabled').checked;
- try {
- const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- orig_name: origName,
- name,
- listen_port: port,
- address: addr,
- mtu,
- comment,
- public_key: pub,
- private_key: priv,
- disabled
- })
- });
- const data = await res.json();
- if (res.ok) {
- showToast('WireGuard Saved', `Interface ${name} configured successfully`, 'success');
- closeAddWGInterfaceModal();
- loadWireGuard(false);
- fetchData(false);
- } else {
- showToast('Error', data.error || 'Failed to save interface', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function startWGInterface(name) {
- try {
- const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/start`, { method: 'POST' });
- if (res.ok) {
- showToast('Interface UP', `Started WireGuard interface ${name}`, 'success');
- loadWireGuard(false);
- fetchData(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function stopWGInterface(name) {
- try {
- const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/stop`, { method: 'POST' });
- if (res.ok) {
- showToast('Interface DOWN', `Stopped WireGuard interface ${name}`, 'info');
- loadWireGuard(false);
- fetchData(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function toggleWGInterfaceState(name, enable) {
- try {
- const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/state`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ enabled: enable })
- });
- if (res.ok) {
- showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
- loadWireGuard(false);
- fetchData(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deleteWGInterface(name) {
- if (!confirm(`Are you sure you want to delete WireGuard interface ${name}? All associated peers will also be removed.`)) return;
- try {
- const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}`, { method: 'DELETE' });
- if (res.ok) {
- showToast('Deleted', `Interface ${name} removed`, 'success');
- loadWireGuard(false);
- fetchData(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- function populateWGPeerIfaceSelect(selectedIface = '') {
- const sel = document.getElementById('wg-peer-modal-iface');
- if (!sel) return;
- sel.innerHTML = '';
- (state.wgInterfaces || []).forEach(i => {
- const opt = document.createElement('option');
- opt.value = i.name;
- opt.innerText = `${i.name} (${i.address || 'No IP'})`;
- if (i.name === selectedIface) opt.selected = true;
- sel.appendChild(opt);
- });
- }
- function openAddWGPeerModal() {
- if ((state.wgInterfaces || []).length === 0) {
- showToast('No Interfaces', 'Please add a WireGuard interface first before adding peers', 'warning');
- openAddWGInterfaceModal();
- return;
- }
- document.getElementById('wg-peer-modal-title').innerText = 'Add WireGuard Peer';
- document.getElementById('wg-peer-modal-edit-orig-iface').value = '';
- document.getElementById('wg-peer-modal-edit-orig-pubkey').value = '';
- populateWGPeerIfaceSelect();
- document.getElementById('wg-peer-modal-name').value = '';
- document.getElementById('wg-peer-modal-pubkey').value = '';
- document.getElementById('wg-peer-modal-allowedips').value = '10.10.0.2/32';
- document.getElementById('wg-peer-modal-endpoint').value = '';
- document.getElementById('wg-peer-modal-port').value = '';
- document.getElementById('wg-peer-modal-keepalive').value = '25';
- document.getElementById('wg-peer-modal-preshared').value = '';
- document.getElementById('wg-peer-modal-disabled').checked = false;
- document.getElementById('wg-peer-key-warning').classList.add('hidden');
- document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
- document.getElementById('wg-peer-modal').classList.remove('hidden');
- }
- function openEditWGPeerModal(ifaceName, pubKey) {
- const peer = (state.wgPeers || []).find(p => p.interface === ifaceName && p.public_key === pubKey);
- if (!peer) {
- showToast('Not Found', 'Peer not found', 'warning');
- return;
- }
- document.getElementById('wg-peer-modal-title').innerText = `Edit WireGuard Peer (${peer.name || ifaceName})`;
- document.getElementById('wg-peer-modal-edit-orig-iface').value = peer.interface;
- document.getElementById('wg-peer-modal-edit-orig-pubkey').value = peer.public_key;
- populateWGPeerIfaceSelect(peer.interface);
- document.getElementById('wg-peer-modal-name').value = peer.name || '';
- document.getElementById('wg-peer-modal-pubkey').value = peer.public_key || '';
- document.getElementById('wg-peer-modal-allowedips').value = (peer.allowed_ips || []).join(', ');
- let epHost = (peer.endpoint_address || '').trim();
- let epPort = peer.endpoint_port || '';
- while (epHost.includes(':') && !epHost.startsWith('[')) {
- const lastColon = epHost.lastIndexOf(':');
- const maybePort = epHost.substring(lastColon + 1);
- if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
- if (!epPort) epPort = parseInt(maybePort, 10);
- epHost = epHost.substring(0, lastColon);
- } else {
- break;
- }
- }
- document.getElementById('wg-peer-modal-endpoint').value = epHost;
- document.getElementById('wg-peer-modal-port').value = epPort;
- document.getElementById('wg-peer-modal-keepalive').value = peer.persistent_keepalive ?? 25;
- document.getElementById('wg-peer-modal-preshared').value = peer.preshared_key || '';
- document.getElementById('wg-peer-modal-disabled').checked = !!peer.disabled;
- document.getElementById('wg-peer-key-warning').classList.add('hidden');
- document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
- document.getElementById('wg-peer-modal').classList.remove('hidden');
- }
- function closeAddWGPeerModal() {
- document.getElementById('wg-peer-modal').classList.add('hidden');
- }
- async function generatePeerKeypairHelper() {
- try {
- const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
- const keys = await res.json();
- if (res.ok) {
- document.getElementById('wg-peer-modal-pubkey').value = keys.public_key;
- document.getElementById('wg-peer-gen-privkey').value = keys.private_key;
- document.getElementById('wg-peer-gen-key-box').classList.remove('hidden');
- checkWGPeerKeyValidity();
- showToast('Keypair Generated', 'Public key inserted and client private key ready to copy', 'info');
- }
- } catch (err) {
- showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
- }
- }
- function copyGeneratedPeerPrivKey() {
- const priv = document.getElementById('wg-peer-gen-privkey').value;
- if (priv) copyToClipboard(priv, 'Client Private Key');
- }
- async function generatePeerPSK() {
- try {
- const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
- const keys = await res.json();
- if (res.ok && keys.private_key) {
- document.getElementById('wg-peer-modal-preshared').value = keys.private_key;
- showToast('PSK Generated', 'Generated 256-bit preshared key', 'info');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- function checkWGPeerKeyValidity() {
- const ifaceName = document.getElementById('wg-peer-modal-iface').value;
- const peerPubKey = document.getElementById('wg-peer-modal-pubkey').value.trim();
- const warningEl = document.getElementById('wg-peer-key-warning');
- if (!warningEl) return;
- const targetIface = (state.wgInterfaces || []).find(i => i.name === ifaceName);
- if (targetIface && targetIface.public_key && peerPubKey && targetIface.public_key === peerPubKey) {
- warningEl.classList.remove('hidden');
- } else {
- warningEl.classList.add('hidden');
- }
- }
- async function submitSaveWGPeer(e) {
- e.preventDefault();
- const origIface = document.getElementById('wg-peer-modal-edit-orig-iface').value.trim();
- const origPubKey = document.getElementById('wg-peer-modal-edit-orig-pubkey').value.trim();
- const iface = document.getElementById('wg-peer-modal-iface').value;
- const name = document.getElementById('wg-peer-modal-name').value.trim();
- const pub = document.getElementById('wg-peer-modal-pubkey').value.trim();
- const allowed = document.getElementById('wg-peer-modal-allowedips').value
- .split(',')
- .map(s => s.trim())
- .filter(s => s.length > 0);
- let epHost = document.getElementById('wg-peer-modal-endpoint').value.trim();
- let epPort = parseInt(document.getElementById('wg-peer-modal-port').value, 10) || 0;
- while (epHost.includes(':') && !epHost.startsWith('[')) {
- const lastColon = epHost.lastIndexOf(':');
- const maybePort = epHost.substring(lastColon + 1);
- if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
- if (!epPort) epPort = parseInt(maybePort, 10);
- epHost = epHost.substring(0, lastColon);
- } else {
- break;
- }
- }
- const keepalive = parseInt(document.getElementById('wg-peer-modal-keepalive').value, 10) || 0;
- const psk = document.getElementById('wg-peer-modal-preshared').value.trim();
- const disabled = document.getElementById('wg-peer-modal-disabled').checked;
- // Validation
- const targetIface = (state.wgInterfaces || []).find(i => i.name === iface);
- if (targetIface && targetIface.public_key === pub) {
- showToast('Invalid Peer Key', 'Peer public key cannot be the same as the interface public key!', 'error');
- return;
- }
- try {
- const res = await fetch(`${API_BASE}/vpn/wireguard/peers`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- orig_interface: origIface,
- orig_public_key: origPubKey,
- interface: iface,
- name,
- public_key: pub,
- allowed_ips: allowed,
- endpoint_address: epHost,
- endpoint_port: epPort,
- persistent_keepalive: keepalive,
- preshared_key: psk,
- disabled
- })
- });
- const data = await res.json();
- if (res.ok) {
- showToast('Peer Saved', `Peer ${name} saved on ${iface}`, 'success');
- closeAddWGPeerModal();
- loadWireGuard(false);
- } else {
- showToast('Error', data.error || 'Failed to save peer', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function toggleWGPeerState(iface, pubkey, enable) {
- try {
- const res = await fetch(`${API_BASE}/vpn/wireguard/peers/state`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ interface: iface, public_key: pubkey, enabled: enable })
- });
- const data = await res.json();
- if (res.ok) {
- showToast(enable ? 'Peer Enabled' : 'Peer Disabled', `Peer state updated on ${iface}`, 'info');
- loadWireGuard(false);
- } else {
- showToast('Error', data.error || 'Failed to update peer state', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deleteWGPeer(iface, pubkey) {
- if (!confirm(`Are you sure you want to remove peer from ${iface}?`)) return;
- try {
- const res = await fetch(`${API_BASE}/vpn/wireguard/peers/delete`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ interface: iface, public_key: pubkey })
- });
- const data = await res.json();
- if (res.ok) {
- showToast('Peer Deleted', 'WireGuard peer removed', 'success');
- loadWireGuard(false);
- } else {
- showToast('Error', data.error || 'Failed to remove peer', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // ======================== IPSec FortiGate Phase 1 & 2 Multi-Tunnel Engine ========================
- function switchIpsecModalTab(tab) {
- const p1Tab = document.getElementById('tab-btn-ipsec-p1');
- const p2Tab = document.getElementById('tab-btn-ipsec-p2');
- const p1Content = document.getElementById('ipsec-tab-content-p1');
- const p2Content = document.getElementById('ipsec-tab-content-p2');
- const stepBtn = document.getElementById('btn-ipsec-switch-step');
- if (tab === 'p1') {
- if (p1Tab) {
- p1Tab.className = 'px-4 py-2 text-xs font-bold border-b-2 border-amber-500 text-amber-300 transition flex items-center gap-2';
- }
- if (p2Tab) {
- p2Tab.className = 'px-4 py-2 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2';
- }
- if (p1Content) p1Content.classList.remove('hidden');
- if (p2Content) p2Content.classList.add('hidden');
- if (stepBtn) stepBtn.innerHTML = 'Next: Phase 2 Selectors →';
- } else {
- if (p1Tab) {
- p1Tab.className = 'px-4 py-2 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2';
- }
- if (p2Tab) {
- p2Tab.className = 'px-4 py-2 text-xs font-bold border-b-2 border-cyan-500 text-cyan-300 transition flex items-center gap-2';
- }
- if (p1Content) p1Content.classList.add('hidden');
- if (p2Content) p2Content.classList.remove('hidden');
- if (stepBtn) stepBtn.innerHTML = '← Back: Phase 1 (IKE)';
- }
- }
- function toggleIpsecPhaseStep() {
- const p1Content = document.getElementById('ipsec-tab-content-p1');
- if (p1Content && !p1Content.classList.contains('hidden')) {
- switchIpsecModalTab('p2');
- } else {
- switchIpsecModalTab('p1');
- }
- }
- function toggleIpsecPskVisibility() {
- const pskInput = document.getElementById('ipsec-modal-psk');
- if (!pskInput) return;
- pskInput.type = pskInput.type === 'password' ? 'text' : 'password';
- }
- function addIpsecLocalSubnet(val = '') {
- const container = document.getElementById('ipsec-modal-local-subnets-container');
- if (!container) return;
- const row = document.createElement('div');
- row.className = 'flex items-center gap-2 ipsec-subnet-row';
- row.innerHTML = `
- <input type="text" value="${escapeHtml(val)}" placeholder="e.g. 192.168.10.0/24 or 10.0.1.0/24" 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">
- <button type="button" onclick="this.closest('.ipsec-subnet-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 local subnet">-</button>
- `;
- container.appendChild(row);
- }
- function addIpsecRemoteSubnet(val = '') {
- const container = document.getElementById('ipsec-modal-remote-subnets-container');
- if (!container) return;
- const row = document.createElement('div');
- row.className = 'flex items-center gap-2 ipsec-subnet-row';
- row.innerHTML = `
- <input type="text" value="${escapeHtml(val)}" placeholder="e.g. 192.168.20.0/24 or 10.0.2.0/24" 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-purple-500">
- <button type="button" onclick="this.closest('.ipsec-subnet-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 remote subnet">-</button>
- `;
- container.appendChild(row);
- }
- function updateIpsecEspProposalFromPFS(val) {
- const prop = document.getElementById('ipsec-modal-espprop');
- if (!prop) return;
- if (val === 'none') {
- prop.value = 'aes256-sha256,aes128-sha256,default';
- } else {
- prop.value = `aes256-sha256-${val},aes128-sha256-${val},default`;
- }
- }
- function updateIpsecIkeProposalFromDH(dh) {
- const el = document.getElementById('ipsec-modal-ikeprop');
- if (el) {
- el.value = `aes256-sha256-${dh},aes128-sha256-${dh},default`;
- }
- }
- function safeSetVal(id, val) {
- const el = document.getElementById(id);
- if (el) el.value = val;
- }
- function safeSetChecked(id, val) {
- const el = document.getElementById(id);
- if (el) el.checked = !!val;
- }
- function safeGetVal(id, def = '') {
- const el = document.getElementById(id);
- return el ? el.value : def;
- }
- async function loadIPSec(populateInputs = true) {
- try {
- const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`);
- const list = await res.json();
- state.ipsecTunnels = Array.isArray(list) ? list : [];
- const activeCount = state.ipsecTunnels.filter(t => t.running || t.status === 'ESTABLISHED').length;
- const badge = document.getElementById('ipsec-sas-badge');
- if (badge) badge.innerText = `${activeCount} Active SAs`;
- const tbody = document.getElementById('ipsec-table-body');
- const empty = document.getElementById('ipsec-empty');
- if (!tbody) return;
- tbody.innerHTML = '';
- if (state.ipsecTunnels.length === 0) {
- if (empty) empty.classList.remove('hidden');
- } else {
- if (empty) empty.classList.add('hidden');
- state.ipsecTunnels.forEach(c => {
- const isEstablished = c.running || c.status === 'ESTABLISHED';
- const tr = document.createElement('tr');
- tr.className = 'hover:bg-slate-800/40 transition text-xs select-none';
- // Local subnets tags
- const localList = (c.local_subnets && c.local_subnets.length > 0) ? c.local_subnets : (c.local_subnet ? [c.local_subnet] : ['0.0.0.0/0']);
- const localBadges = localList.map(s => `<span class="px-1.5 py-0.5 rounded bg-cyan-950/60 border border-cyan-800/60 text-cyan-300 font-mono text-[10px] mr-1">${escapeHtml(s)}</span>`).join('');
- // Remote subnets tags
- const remoteList = (c.remote_subnets && c.remote_subnets.length > 0) ? c.remote_subnets : (c.remote_subnet ? [c.remote_subnet] : ['0.0.0.0/0']);
- const remoteBadges = remoteList.map(s => `<span class="px-1.5 py-0.5 rounded bg-purple-950/60 border border-purple-800/60 text-purple-300 font-mono text-[10px] mr-1">${escapeHtml(s)}</span>`).join('');
- const ikeVersionBadge = (c.ike_version || 'ikev2').toUpperCase();
- const p2Name = c.phase2_name || `${c.name}_p2`;
- tr.innerHTML = `
- <td class="py-2.5 px-3 text-center">
- ${isEstablished ? `
- <span class="inline-flex items-center gap-1.5 text-emerald-400 font-mono font-bold text-[11px]" title="Active SA Established">
- <span class="w-2.5 h-2.5 rounded-full bg-emerald-400 animate-pulse"></span>
- <span>UP</span>
- </span>
- ` : (c.disabled ? `
- <span class="inline-flex items-center gap-1.5 text-slate-500 font-mono text-[11px]" title="Tunnel Disabled">
- <span class="w-2 h-2 rounded-full bg-rose-500"></span>
- <span>DOWN</span>
- </span>
- ` : `
- <span class="inline-flex items-center gap-1.5 text-amber-400 font-mono text-[11px]" title="Disconnected / Idle">
- <span class="w-2 h-2 rounded-full bg-amber-400"></span>
- <span>IDLE</span>
- </span>
- `)}
- </td>
- <td class="py-2.5 px-4 font-bold text-white">
- <div class="flex items-center gap-2">
- <span class="text-amber-400">🛡</span>
- <div>
- <div>${escapeHtml(c.name)}</div>
- <div class="text-[10px] text-slate-500 font-normal">P2: ${escapeHtml(p2Name)}</div>
- </div>
- </div>
- </td>
- <td class="py-2.5 px-4 text-slate-300 font-mono font-medium">${escapeHtml(c.remote_addrs || '%any')}</td>
- <td class="py-2.5 px-4 font-sans">
- <div class="flex items-center gap-1.5">
- <span class="px-1.5 py-0.5 rounded bg-amber-500/10 text-amber-300 border border-amber-500/30 font-mono text-[10px] font-semibold">${ikeVersionBadge}</span>
- <span class="text-[10px] text-slate-400">${c.auth_method || 'PSK'}</span>
- </div>
- </td>
- <td class="py-2.5 px-4">
- <div class="space-y-1">
- <div class="flex items-center flex-wrap gap-1">
- <span class="text-[9px] text-cyan-400 uppercase font-bold mr-1">Local:</span>
- ${localBadges}
- </div>
- <div class="flex items-center flex-wrap gap-1">
- <span class="text-[9px] text-purple-400 uppercase font-bold mr-1">Remote:</span>
- ${remoteBadges}
- </div>
- </div>
- </td>
- <td class="py-2.5 px-4 font-mono text-[11px] text-slate-400">
- <div class="truncate max-w-[140px]" title="${escapeHtml(c.esp_proposals || '')}">
- ${escapeHtml(c.esp_proposals || 'aes256-sha256')}
- </div>
- <div class="text-[10px] text-slate-500">PFS: ${escapeHtml(c.pfs_group || 'modp2048')}</div>
- </td>
- <td class="py-2.5 px-4 text-right space-x-2 font-sans">
- ${isEstablished ? `
- <button onclick="stopIPSecTunnel('${c.name}')" class="px-2 py-0.5 text-xs bg-rose-500/20 text-rose-400 hover:bg-rose-500/30 rounded border border-rose-500/30 font-medium">Bring Down</button>
- ` : `
- <button onclick="startIPSecTunnel('${c.name}')" class="px-2 py-0.5 text-xs bg-emerald-500/20 text-emerald-400 hover:bg-emerald-500/30 rounded border border-emerald-500/30 font-semibold">Bring Up</button>
- `}
- <button onclick="toggleIPSecState('${c.name}', ${c.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
- ${c.disabled ? 'Enable' : 'Disable'}
- </button>
- <button onclick="openEditIPSecModal('${c.name}')" class="text-xs text-amber-400 hover:text-amber-300">Edit</button>
- <button onclick="deleteIPSecConn('${c.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
- </td>
- `;
- tbody.appendChild(tr);
- });
- }
- } catch (err) {
- console.error('Failed to load IPSec:', err);
- }
- }
- function openAddIPSecModal() {
- const modal = document.getElementById('ipsec-modal');
- if (!modal) return;
- const title = document.getElementById('ipsec-modal-title');
- if (title) title.innerText = 'Configure IPSec Site-to-Site Tunnel';
-
- // Phase 1 Fields
- safeSetVal('ipsec-modal-name', `tunnel-${(state.ipsecTunnels || []).length + 1}`);
- const nameEl = document.getElementById('ipsec-modal-name');
- if (nameEl) nameEl.readOnly = false;
- safeSetVal('ipsec-modal-ikeversion', 'ikev2');
- safeSetVal('ipsec-modal-ikever', 'ikev2');
- safeSetVal('ipsec-modal-remotegw', '');
- safeSetVal('ipsec-modal-localaddrs', '');
- safeSetVal('ipsec-modal-comments', '');
- safeSetVal('ipsec-modal-psk', '');
- safeSetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
- safeSetVal('ipsec-modal-dhgroup', 'modp2048');
- safeSetVal('ipsec-modal-ikekeylife', '86400');
- safeSetVal('ipsec-modal-localid', '');
- safeSetVal('ipsec-modal-remoteid', '');
- safeSetVal('ipsec-modal-dpd', 'on-demand');
- // Phase 2 Fields
- safeSetVal('ipsec-modal-p2name', `tunnel-${(state.ipsecTunnels || []).length + 1}_p2`);
- safeSetVal('ipsec-modal-espkeylife', '28800');
- safeSetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
- safeSetVal('ipsec-modal-pfsgroup', 'modp2048');
- safeSetChecked('ipsec-modal-autostart', true);
- safeSetChecked('ipsec-modal-disabled', false);
- // Clear & Populate default dynamic subnets
- const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
- const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
- if (localContainer) {
- localContainer.innerHTML = '';
- addIpsecLocalSubnet('192.168.10.0/24');
- }
- if (remoteContainer) {
- remoteContainer.innerHTML = '';
- addIpsecRemoteSubnet('192.168.20.0/24');
- }
- switchIpsecModalTab('p1');
- modal.classList.remove('hidden');
- }
- function openEditIPSecModal(name) {
- const modal = document.getElementById('ipsec-modal');
- if (!modal) return;
- const conn = (state.ipsecTunnels || []).find(c => c.name === name);
- if (!conn) return;
- const title = document.getElementById('ipsec-modal-title');
- if (title) title.innerText = `Edit IPSec Tunnel: ${name}`;
-
- // Phase 1 Fields
- safeSetVal('ipsec-modal-name', conn.name);
- const nameEl = document.getElementById('ipsec-modal-name');
- if (nameEl) nameEl.readOnly = true;
- safeSetVal('ipsec-modal-ikeversion', conn.ike_version || 'ikev2');
- safeSetVal('ipsec-modal-ikever', conn.ike_version || 'ikev2');
- safeSetVal('ipsec-modal-remotegw', conn.remote_addrs || '');
- safeSetVal('ipsec-modal-localaddrs', conn.local_addrs || '');
- safeSetVal('ipsec-modal-comments', conn.comment || '');
- safeSetVal('ipsec-modal-psk', conn.preshared_key || '');
- safeSetVal('ipsec-modal-ikeprop', conn.ike_proposals || 'aes256-sha256-modp2048,default');
- safeSetVal('ipsec-modal-ikekeylife', conn.ike_keylife || 86400);
- safeSetVal('ipsec-modal-localid', conn.local_id || '');
- safeSetVal('ipsec-modal-remoteid', conn.remote_id || '');
- safeSetVal('ipsec-modal-dpd', conn.dpd || 'on-demand');
- // Phase 2 Fields
- safeSetVal('ipsec-modal-p2name', conn.phase2_name || `${conn.name}_p2`);
- safeSetVal('ipsec-modal-espkeylife', conn.esp_keylife || 28800);
- safeSetVal('ipsec-modal-espprop', conn.esp_proposals || 'aes256-sha256-modp2048,default');
- safeSetVal('ipsec-modal-pfsgroup', conn.pfs_group || 'modp2048');
- safeSetChecked('ipsec-modal-autostart', conn.auto_start ?? true);
- safeSetChecked('ipsec-modal-disabled', !!conn.disabled);
- // Populate dynamic subnets
- const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
- const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
-
- if (localContainer) {
- localContainer.innerHTML = '';
- const locals = (conn.local_subnets && conn.local_subnets.length > 0) ? conn.local_subnets : (conn.local_subnet ? [conn.local_subnet] : ['192.168.10.0/24']);
- locals.forEach(s => addIpsecLocalSubnet(s));
- }
- if (remoteContainer) {
- remoteContainer.innerHTML = '';
- const remotes = (conn.remote_subnets && conn.remote_subnets.length > 0) ? conn.remote_subnets : (conn.remote_subnet ? [conn.remote_subnet] : ['192.168.20.0/24']);
- remotes.forEach(s => addIpsecRemoteSubnet(s));
- }
- switchIpsecModalTab('p1');
- modal.classList.remove('hidden');
- }
- function closeAddIPSecModal() {
- const modal = document.getElementById('ipsec-modal');
- if (modal) modal.classList.add('hidden');
- }
- async function submitSaveIPSec(e) {
- if (e) e.preventDefault();
- const name = safeGetVal('ipsec-modal-name').trim();
- if (!name) {
- showToast('Error', 'Tunnel name is required', 'error');
- return;
- }
- const ikeVersion = safeGetVal('ipsec-modal-ikeversion') || safeGetVal('ipsec-modal-ikever', 'ikev2');
- const remotegw = safeGetVal('ipsec-modal-remotegw').trim();
- const localAddrs = safeGetVal('ipsec-modal-localaddrs').trim() || '%any';
- const comments = safeGetVal('ipsec-modal-comments').trim();
- const psk = safeGetVal('ipsec-modal-psk');
- const ikeProposals = safeGetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,default').trim();
- const ikeKeylife = parseInt(safeGetVal('ipsec-modal-ikekeylife', '86400'), 10) || 86400;
- const localId = safeGetVal('ipsec-modal-localid').trim();
- const remoteId = safeGetVal('ipsec-modal-remoteid').trim();
- const dpd = safeGetVal('ipsec-modal-dpd', 'on-demand');
- const phase2Name = safeGetVal('ipsec-modal-p2name').trim() || `${name}_p2`;
- const espProposals = safeGetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,default').trim();
- const espKeylife = parseInt(safeGetVal('ipsec-modal-espkeylife', '28800'), 10) || 28800;
- const pfsGroup = safeGetVal('ipsec-modal-pfsgroup', 'modp2048');
- const autostart = document.getElementById('ipsec-modal-autostart')?.checked ?? true;
- const disabled = document.getElementById('ipsec-modal-disabled')?.checked ?? false;
- // Scrape dynamic local and remote subnets
- const localInputs = document.querySelectorAll('#ipsec-modal-local-subnets-container input');
- const localSubnets = [];
- localInputs.forEach(inp => {
- const v = inp.value.trim();
- if (v) localSubnets.push(v);
- });
- const remoteInputs = document.querySelectorAll('#ipsec-modal-remote-subnets-container input');
- const remoteSubnets = [];
- remoteInputs.forEach(inp => {
- const v = inp.value.trim();
- if (v) remoteSubnets.push(v);
- });
- try {
- const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- name,
- comment: comments,
- ike_version: ikeVersion,
- local_addrs: localAddrs,
- remote_addrs: remotegw,
- preshared_key: psk,
- ike_proposals: ikeProposals,
- ike_keylife: ikeKeylife,
- local_id: localId,
- remote_id: remoteId,
- dpd: dpd,
- phase2_name: phase2Name,
- esp_proposals: espProposals,
- esp_keylife: espKeylife,
- pfs_group: pfsGroup,
- pfs: pfsGroup !== 'none',
- local_subnets: localSubnets,
- remote_subnets: remoteSubnets,
- local_subnet: localSubnets[0] || '0.0.0.0/0',
- remote_subnet: remoteSubnets[0] || '0.0.0.0/0',
- auto_start: autostart,
- disabled
- })
- });
- if (res.ok) {
- showToast('IPSec Saved', `FortiGate Tunnel ${name} configured`, 'success');
- closeAddIPSecModal();
- loadIPSec(false);
- } else {
- const err = await res.json();
- showToast('Error', err.error || 'Failed to save IPSec tunnel', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function startIPSecTunnel(name) {
- try {
- const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/start`, { method: 'POST' });
- if (res.ok) {
- showToast('Initiating Tunnel', `Attempting SA handshake for ${name}...`, 'info');
- setTimeout(() => loadIPSec(false), 2000);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function stopIPSecTunnel(name) {
- try {
- const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/stop`, { method: 'POST' });
- if (res.ok) {
- showToast('Terminated', `IPSec SA for ${name} closed`, 'info');
- loadIPSec(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function toggleIPSecState(name, enable) {
- try {
- const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/state`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ enabled: enable })
- });
- if (res.ok) {
- showToast(enable ? 'Enabled' : 'Disabled', `IPSec tunnel ${name} updated`, 'info');
- loadIPSec(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deleteIPSecConn(name) {
- if (!confirm(`Are you sure you want to delete IPSec tunnel ${name}?`)) return;
- try {
- const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}`, { method: 'DELETE' });
- if (res.ok) {
- showToast('Deleted', `IPSec connection ${name} removed`, 'success');
- loadIPSec(false);
- fetchData(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // ======================== L2TP Multi-Instance ========================
- async function loadL2TP(populateInputs = true) {
- try {
- if (!state.pppProfiles || state.pppProfiles.length === 0) {
- await fetchPPPProfilesList();
- }
- const res = await fetch(`${API_BASE}/vpn/l2tp/clients`);
- const list = await res.json();
- state.l2tpList = Array.isArray(list) ? list : [];
- const badge = document.getElementById('l2tp-count-badge');
- if (badge) badge.innerText = `${state.l2tpList.length} Client${state.l2tpList.length !== 1 ? 's' : ''}`;
- const tbody = document.getElementById('l2tp-table-body');
- const empty = document.getElementById('l2tp-empty');
- if (!tbody) return;
- tbody.innerHTML = '';
- if (state.l2tpList.length === 0) {
- if (empty) empty.classList.remove('hidden');
- } else {
- if (empty) empty.classList.add('hidden');
- state.l2tpList.forEach(inst => {
- const tr = document.createElement('tr');
- tr.className = 'hover:bg-slate-800/40 transition text-xs';
- tr.innerHTML = `
- <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
- <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
- <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.connect_to)}</td>
- <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
- <td class="py-2.5 px-3 font-mono text-cyan-300"><span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 border border-slate-700">${escapeHtml(inst.profile || 'default-encryption')}</span></td>
- <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${escapeHtml(inst.assigned_ip || '-')}</td>
- <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
- <td class="py-2.5 px-3 text-center">
- <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'}">
- ${inst.default_route ? 'Yes' : 'No'}
- </span>
- </td>
- <td class="py-2.5 px-3 text-right space-x-2 font-sans">
- ${inst.running ? `
- <button onclick="disconnectL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
- ` : `
- <button onclick="connectL2TPInstance('${escapeHtml(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>
- `}
- <button onclick="toggleL2TPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
- ${inst.disabled ? 'Enable' : 'Disable'}
- </button>
- <button onclick="openEditL2TPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
- <button onclick="deleteL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
- </td>
- `;
- tbody.appendChild(tr);
- });
- }
- } catch (err) {
- console.error('Failed to load L2TP:', err);
- }
- }
- async function openAddL2TPModal() {
- if (!state.pppProfiles || state.pppProfiles.length === 0) {
- await fetchPPPProfilesList();
- }
- document.getElementById('l2tp-modal-title').innerText = 'Add L2TP Client Interface';
- document.getElementById('l2tp-modal-name').value = `l2tp-out${(state.l2tpList || []).length + 1}`;
- document.getElementById('l2tp-modal-name').readOnly = false;
- document.getElementById('l2tp-modal-server').value = '';
- document.getElementById('l2tp-modal-user').value = '';
- document.getElementById('l2tp-modal-pass').value = '';
- document.getElementById('l2tp-modal-ipsec').value = '';
- document.getElementById('l2tp-modal-defroute').checked = true;
- document.getElementById('l2tp-modal-disabled').checked = false;
- populateProfileSelect('l2tp-modal-profile', 'default-encryption', 'default-encryption');
- document.getElementById('l2tp-modal').classList.remove('hidden');
- }
- async function openEditL2TPModal(name) {
- if (!state.pppProfiles || state.pppProfiles.length === 0) {
- await fetchPPPProfilesList();
- }
- const inst = (state.l2tpList || []).find(i => i.name === name);
- if (!inst) return;
- document.getElementById('l2tp-modal-title').innerText = `Edit L2TP Client: ${name}`;
- document.getElementById('l2tp-modal-name').value = inst.name;
- document.getElementById('l2tp-modal-name').readOnly = true;
- document.getElementById('l2tp-modal-server').value = inst.connect_to || '';
- document.getElementById('l2tp-modal-user').value = inst.username || '';
- document.getElementById('l2tp-modal-pass').value = inst.password || '';
- document.getElementById('l2tp-modal-ipsec').value = inst.ipsec_secret || '';
- document.getElementById('l2tp-modal-defroute').checked = inst.default_route ?? true;
- document.getElementById('l2tp-modal-disabled').checked = !!inst.disabled;
- populateProfileSelect('l2tp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
- document.getElementById('l2tp-modal').classList.remove('hidden');
- }
- function closeL2TPModal() {
- document.getElementById('l2tp-modal').classList.add('hidden');
- }
- async function submitSaveL2TP(e) {
- e.preventDefault();
- const name = document.getElementById('l2tp-modal-name').value.trim();
- const server = document.getElementById('l2tp-modal-server').value.trim();
- const user = document.getElementById('l2tp-modal-user').value.trim();
- const pass = document.getElementById('l2tp-modal-pass').value;
- const profile = document.getElementById('l2tp-modal-profile')?.value || 'default-encryption';
- const ipsec = document.getElementById('l2tp-modal-ipsec').value;
- const defRoute = document.getElementById('l2tp-modal-defroute').checked;
- const disabled = document.getElementById('l2tp-modal-disabled').checked;
- try {
- const res = await fetch(`${API_BASE}/vpn/l2tp/clients`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- name,
- connect_to: server,
- username: user,
- password: pass,
- profile: profile,
- ipsec_secret: ipsec,
- default_route: defRoute,
- disabled
- })
- });
- if (res.ok) {
- showToast('L2TP Saved', `Client ${name} configuration saved`, 'success');
- closeL2TPModal();
- loadL2TP(false);
- fetchData(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function connectL2TPInstance(name) {
- try {
- const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
- if (res.ok) {
- showToast('Connecting', `Dialing L2TP ${name}...`, 'info');
- setTimeout(() => loadL2TP(false), 2000);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function disconnectL2TPInstance(name) {
- try {
- const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
- if (res.ok) {
- showToast('Disconnected', `L2TP tunnel ${name} terminated`, 'info');
- loadL2TP(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function toggleL2TPState(name, enable) {
- try {
- const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/state`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ enabled: enable })
- });
- if (res.ok) {
- showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
- loadL2TP(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deleteL2TPInstance(name) {
- if (!confirm(`Are you sure you want to delete L2TP client ${name}?`)) return;
- try {
- const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
- if (res.ok) {
- showToast('Deleted', `L2TP client ${name} removed`, 'success');
- loadL2TP(false);
- fetchData(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // ======================== PPTP Multi-Instance ========================
- async function loadPPTP(populateInputs = true) {
- try {
- if (!state.pppProfiles || state.pppProfiles.length === 0) {
- await fetchPPPProfilesList();
- }
- const res = await fetch(`${API_BASE}/vpn/pptp/clients`);
- const list = await res.json();
- state.pptpList = Array.isArray(list) ? list : [];
- const badge = document.getElementById('pptp-count-badge');
- if (badge) badge.innerText = `${state.pptpList.length} Client${state.pptpList.length !== 1 ? 's' : ''}`;
- const tbody = document.getElementById('pptp-table-body');
- const empty = document.getElementById('pptp-empty');
- if (!tbody) return;
- tbody.innerHTML = '';
- if (state.pptpList.length === 0) {
- if (empty) empty.classList.remove('hidden');
- } else {
- if (empty) empty.classList.add('hidden');
- state.pptpList.forEach(inst => {
- const tr = document.createElement('tr');
- tr.className = 'hover:bg-slate-800/40 transition text-xs';
- tr.innerHTML = `
- <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
- <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
- <td class="py-2.5 px-3 text-purple-400 font-mono">${escapeHtml(inst.connect_to)}</td>
- <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
- <td class="py-2.5 px-3 font-mono text-purple-300"><span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 border border-slate-700">${escapeHtml(inst.profile || 'default-encryption')}</span></td>
- <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${escapeHtml(inst.assigned_ip || '-')}</td>
- <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
- <td class="py-2.5 px-3 text-center">
- <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'}">
- ${inst.require_mppe ? 'MPPE-128' : 'None'}
- </span>
- </td>
- <td class="py-2.5 px-3 text-right space-x-2 font-sans">
- ${inst.running ? `
- <button onclick="disconnectPPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
- ` : `
- <button onclick="connectPPTPInstance('${escapeHtml(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>
- `}
- <button onclick="togglePPTPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
- ${inst.disabled ? 'Enable' : 'Disable'}
- </button>
- <button onclick="openEditPPTPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
- <button onclick="deletePPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
- </td>
- `;
- tbody.appendChild(tr);
- });
- }
- } catch (err) {
- console.error('Failed to load PPTP:', err);
- }
- }
- async function openAddPPTPModal() {
- if (!state.pppProfiles || state.pppProfiles.length === 0) {
- await fetchPPPProfilesList();
- }
- document.getElementById('pptp-modal-title').innerText = 'Add PPTP Client Interface';
- document.getElementById('pptp-modal-name').value = `pptp-out${(state.pptpList || []).length + 1}`;
- document.getElementById('pptp-modal-name').readOnly = false;
- document.getElementById('pptp-modal-server').value = '';
- document.getElementById('pptp-modal-user').value = '';
- document.getElementById('pptp-modal-pass').value = '';
- document.getElementById('pptp-modal-mppe').checked = true;
- document.getElementById('pptp-modal-defroute').checked = true;
- document.getElementById('pptp-modal-disabled').checked = false;
- populateProfileSelect('pptp-modal-profile', 'default-encryption', 'default-encryption');
- document.getElementById('pptp-modal').classList.remove('hidden');
- }
- async function openEditPPTPModal(name) {
- if (!state.pppProfiles || state.pppProfiles.length === 0) {
- await fetchPPPProfilesList();
- }
- const inst = (state.pptpList || []).find(i => i.name === name);
- if (!inst) return;
- document.getElementById('pptp-modal-title').innerText = `Edit PPTP Client: ${name}`;
- document.getElementById('pptp-modal-name').value = inst.name;
- document.getElementById('pptp-modal-name').readOnly = true;
- document.getElementById('pptp-modal-server').value = inst.connect_to || '';
- document.getElementById('pptp-modal-user').value = inst.username || '';
- document.getElementById('pptp-modal-pass').value = inst.password || '';
- document.getElementById('pptp-modal-mppe').checked = inst.require_mppe ?? true;
- document.getElementById('pptp-modal-defroute').checked = inst.default_route ?? true;
- document.getElementById('pptp-modal-disabled').checked = !!inst.disabled;
- populateProfileSelect('pptp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
- document.getElementById('pptp-modal').classList.remove('hidden');
- }
- function closePPTPModal() {
- document.getElementById('pptp-modal').classList.add('hidden');
- }
- async function submitSavePPTP(e) {
- e.preventDefault();
- const name = document.getElementById('pptp-modal-name').value.trim();
- const server = document.getElementById('pptp-modal-server').value.trim();
- const user = document.getElementById('pptp-modal-user').value.trim();
- const pass = document.getElementById('pptp-modal-pass').value;
- const profile = document.getElementById('pptp-modal-profile')?.value || 'default-encryption';
- const mppe = document.getElementById('pptp-modal-mppe').checked;
- const defRoute = document.getElementById('pptp-modal-defroute').checked;
- const disabled = document.getElementById('pptp-modal-disabled').checked;
- try {
- const res = await fetch(`${API_BASE}/vpn/pptp/clients`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- name,
- connect_to: server,
- username: user,
- password: pass,
- profile: profile,
- require_mppe: mppe,
- default_route: defRoute,
- auto_reconnect: true,
- disabled
- })
- });
- if (res.ok) {
- showToast('PPTP Saved', `Client ${name} configuration saved`, 'success');
- closePPTPModal();
- loadPPTP(false);
- fetchData(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function connectPPTPInstance(name) {
- try {
- const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
- if (res.ok) {
- showToast('Connecting', `Dialing PPTP ${name}...`, 'info');
- setTimeout(() => loadPPTP(false), 2000);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function disconnectPPTPInstance(name) {
- try {
- const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
- if (res.ok) {
- showToast('Disconnected', `PPTP tunnel ${name} terminated`, 'info');
- loadPPTP(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function togglePPTPState(name, enable) {
- try {
- const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/state`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ enabled: enable })
- });
- if (res.ok) {
- showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
- loadPPTP(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deletePPTPInstance(name) {
- if (!confirm(`Are you sure you want to delete PPTP client ${name}?`)) return;
- try {
- const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
- if (res.ok) {
- showToast('Deleted', `PPTP client ${name} removed`, 'success');
- loadPPTP(false);
- fetchData(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // ---------------- Modal & Helper Functions ----------------
- function openVlanModal(defaultParent = '') {
- const select = document.getElementById('vlan-parent');
- select.innerHTML = '';
- const allIfaces = state.interfaces || [];
- const eligible = allIfaces.filter(i => supportsVLAN(i));
- if (eligible.length === 0) {
- const opt = document.createElement('option');
- opt.value = '';
- opt.innerText = 'No VLAN-capable interfaces available';
- select.appendChild(opt);
- } else {
- eligible.forEach(i => {
- const opt = document.createElement('option');
- opt.value = i.name;
- opt.innerText = `${i.name} (${i.role || i.type || 'Ethernet'} - ${i.state})`;
- if (i.name === defaultParent) opt.selected = true;
- select.appendChild(opt);
- });
- }
- document.getElementById('vlan-id').value = '';
- document.getElementById('vlan-name').value = '';
- document.getElementById('vlan-ip').value = '';
- document.getElementById('vlan-desc').value = '';
- populateRoleSelects('LAN');
- autoSuggestVlanName();
- document.getElementById('vlan-modal').classList.remove('hidden');
- }
- function closeVlanModal() {
- document.getElementById('vlan-modal').classList.add('hidden');
- }
- function autoSuggestVlanName() {
- const parent = document.getElementById('vlan-parent').value;
- if (!parent) return;
- const id = document.getElementById('vlan-id').value;
- const nameInput = document.getElementById('vlan-name');
- if (parent && id) nameInput.placeholder = `${parent}.${id}`;
- }
- function setSubnetPreset(cidr) {
- const ipInput = document.getElementById('vlan-ip');
- const id = document.getElementById('vlan-id').value || '10';
- ipInput.value = `192.168.${id}.1${cidr}`;
- }
- async function submitCreateVlan(e) {
- e.preventDefault();
- const btn = document.getElementById('vlan-submit-btn');
- btn.disabled = true;
- btn.innerText = 'Creating...';
- const parent = document.getElementById('vlan-parent').value;
- if (!parent) {
- showToast('Error', 'Please select a valid VLAN-capable parent interface', 'error');
- btn.disabled = false;
- btn.innerText = 'Create VLAN';
- return;
- }
- const id = parseInt(document.getElementById('vlan-id').value, 10);
- const name = document.getElementById('vlan-name').value.trim();
- const ip = document.getElementById('vlan-ip').value.trim();
- const role = document.getElementById('vlan-role').value;
- const desc = document.getElementById('vlan-desc').value.trim();
- try {
- const res = await fetch(`${API_BASE}/vlans`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- parent_name: parent,
- vlan_id: id,
- name: name,
- ip_address: ip,
- role: role,
- description: desc,
- mtu: 1500,
- auto_up: true
- })
- });
- const data = await res.json();
- if (res.ok) {
- showToast('VLAN Created', `Created ${data.name} (VLAN ${data.vlan_id})`, 'success');
- state.expandedParents.add(parent);
- closeVlanModal();
- await fetchData(true);
- if (state.activeTab !== 'interfaces') navigate('interfaces');
- } else {
- showToast('Creation Failed', data.message || 'Failed to create VLAN', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- } finally {
- btn.disabled = false;
- btn.innerText = 'Create VLAN';
- }
- }
- async function confirmDeleteVlan(name) {
- if (!confirm(`Delete VLAN interface ${name}?`)) return;
- try {
- const res = await fetch(`${API_BASE}/vlans/${encodeURIComponent(name)}`, { method: 'DELETE' });
- if (res.ok) {
- showToast('VLAN Deleted', `Interface ${name} removed`, 'success');
- closeIfaceModal();
- fetchData(true);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- function openIfaceModal(name) {
- const iface = (state.interfaces || []).find(i => i.name === name);
- if (!iface) return;
- state.currentModalIface = iface.name;
- document.getElementById('modal-iface-name').innerText = iface.name;
- document.getElementById('modal-iface-badge').innerText = iface.is_vlan ? `VLAN ${iface.vlan_id}` : iface.type;
- document.getElementById('modal-iface-mtu').value = iface.mtu;
- populateRoleSelects(iface.role || 'LAN');
- document.getElementById('modal-iface-desc').value = iface.description || '';
- const nameInput = document.getElementById('modal-iface-new-name');
- const renameBtn = document.getElementById('modal-btn-rename');
- const renameHelp = document.getElementById('modal-iface-rename-help');
- if (nameInput) {
- nameInput.value = iface.name;
- if (iface.name === 'lo' || iface.type === 'loopback') {
- nameInput.disabled = true;
- if (renameBtn) renameBtn.disabled = true;
- if (renameHelp) renameHelp.innerText = 'Loopback interface cannot be renamed.';
- } else {
- nameInput.disabled = false;
- if (renameBtn) renameBtn.disabled = false;
- if (renameHelp) renameHelp.innerText = 'Device name in Linux (max 15 characters). Automatically preserves operational link state and metadata.';
- }
- }
- const delBtn = document.getElementById('modal-delete-vlan-btn');
- if (iface.is_vlan) {
- delBtn.classList.remove('hidden');
- } else {
- delBtn.classList.add('hidden');
- }
- renderModalIPs(iface);
- document.getElementById('iface-modal').classList.remove('hidden');
- }
- function renderModalIPs(iface) {
- const container = document.getElementById('modal-ip-list');
- container.innerHTML = '';
- const addrs = [...(iface.ipv4 || []), ...(iface.ipv6 || [])];
- if (addrs.length === 0) {
- container.innerHTML = `<span class="text-slate-500 text-xs font-sans">No IP addresses currently bound</span>`;
- return;
- }
- addrs.forEach(addr => {
- const row = document.createElement('div');
- row.className = 'flex items-center justify-between p-2 rounded bg-slate-900 border border-slate-800';
- row.innerHTML = `
- <span class="text-white">${addr}</span>
- <button onclick="removeInterfaceIP('${addr}')" class="text-[11px] text-rose-400 hover:text-rose-300 font-sans">Remove</button>
- `;
- container.appendChild(row);
- });
- }
- function closeIfaceModal() {
- document.getElementById('iface-modal').classList.add('hidden');
- state.currentModalIface = null;
- }
- async function setIfaceState(name, newState) {
- const target = name || state.currentModalIface;
- if (!target) return;
- await toggleInterfaceState(target, newState);
- const updated = (state.interfaces || []).find(i => i.name === target);
- if (updated) openIfaceModal(target);
- }
- async function applyMTU() {
- const mtu = parseInt(document.getElementById('modal-iface-mtu').value, 10);
- try {
- const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/mtu`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ mtu })
- });
- if (res.ok) {
- showToast('MTU Applied', `Set MTU to ${mtu} on ${state.currentModalIface}`, 'success');
- fetchData(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function addInterfaceIP() {
- const ip = document.getElementById('modal-new-ip').value.trim();
- if (!ip) return;
- try {
- const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ ip })
- });
- if (res.ok) {
- showToast('IP Added', `Bound ${ip} to ${state.currentModalIface}`, 'success');
- document.getElementById('modal-new-ip').value = '';
- await fetchData(false);
- const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
- if (iface) renderModalIPs(iface);
- } else {
- const err = await res.json();
- showToast('Error', err.error || err.message || 'Failed to add IP address', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function removeInterfaceIP(ip) {
- if (!confirm(`Remove IP ${ip}?`)) return;
- try {
- const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
- method: 'DELETE',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ ip })
- });
- if (res.ok) {
- showToast('IP Removed', `Removed ${ip}`, 'success');
- await fetchData(false);
- const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
- if (iface) renderModalIPs(iface);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function renameInterface() {
- const oldName = state.currentModalIface;
- const newNameInput = document.getElementById('modal-iface-new-name');
- const newName = (newNameInput?.value || '').trim();
- if (!oldName) return;
- if (!newName) {
- showToast('Warning', 'Interface name cannot be empty', 'warning');
- return;
- }
- if (newName === oldName) {
- showToast('Info', `Interface name is already "${oldName}"`, 'info');
- return;
- }
- if (newName.length > 15) {
- showToast('Validation Error', 'Interface name cannot exceed 15 characters (Linux IFNAMSIZ)', 'error');
- return;
- }
- if (!/^[a-zA-Z0-9_][a-zA-Z0-9_.-]*$/.test(newName)) {
- showToast('Validation Error', 'Name must contain only alphanumeric characters, underscores, hyphens or dots', 'error');
- return;
- }
- const renameBtn = document.getElementById('modal-btn-rename');
- if (renameBtn) {
- renameBtn.disabled = true;
- renameBtn.innerHTML = `<span class="animate-spin inline-block mr-1">⟳</span> Renaming...`;
- }
- try {
- const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(oldName)}/rename`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ new_name: newName })
- });
- const data = await res.json();
- if (!res.ok) {
- showToast('Rename Failed', data.error || data.message || 'Failed to rename interface', 'error');
- return;
- }
- showToast('Interface Renamed', `Successfully renamed ${oldName} → ${newName}`, 'success');
- state.currentModalIface = newName;
- document.getElementById('modal-iface-name').innerText = newName;
- // Refresh application state
- await fetchData(false);
- const updated = (state.interfaces || []).find(i => i.name === newName);
- if (updated) {
- openIfaceModal(newName);
- } else {
- closeIfaceModal();
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- } finally {
- if (renameBtn) {
- renameBtn.disabled = false;
- renameBtn.innerHTML = `
- <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
- <span>Rename</span>
- `;
- }
- }
- }
- async function saveInterfaceMetadata() {
- const oldName = state.currentModalIface;
- const newName = (document.getElementById('modal-iface-new-name')?.value || '').trim();
- const role = document.getElementById('modal-iface-role').value;
- const desc = document.getElementById('modal-iface-desc').value.trim();
- let targetName = oldName;
- // If user changed the name before clicking Save Changes, execute rename first
- if (newName && newName !== oldName && oldName !== 'lo') {
- try {
- const renameRes = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(oldName)}/rename`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ new_name: newName })
- });
- const data = await renameRes.json();
- if (!renameRes.ok) {
- showToast('Rename Failed', data.error || data.message || 'Could not rename interface', 'error');
- return;
- }
- targetName = newName;
- state.currentModalIface = newName;
- showToast('Renamed', `Interface renamed from ${oldName} to ${newName}`, 'success');
- } catch (err) {
- showToast('Error', err.message, 'error');
- return;
- }
- }
- try {
- const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(targetName)}/metadata`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ role, description: desc })
- });
- if (res.ok) {
- showToast('Saved', 'Interface configuration updated', 'success');
- closeIfaceModal();
- fetchData(false);
- } else {
- const err = await res.json();
- showToast('Error', err.error || err.message || 'Failed to save metadata', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // ======================== IPTABLES FIREWALL ========================
- state.fwSubTab = 'filter';
- state.routesSubTab = 'routes';
- function nativeNATChain(chain) {
- const value = (chain || '').toLowerCase();
- if (value === 'dstnat') return 'prerouting';
- if (value === 'srcnat') return 'postrouting';
- return ['prerouting', 'input', 'output', 'postrouting'].includes(value) ? value : (chain || '');
- }
- function nativeFirewallTarget(action) {
- const name = (action || '').toLowerCase();
- return ({'src-nat':'SNAT', 'dst-nat':'DNAT', 'add-src-to-address-list':'SET (add source)', 'add-dst-to-address-list':'SET (add destination)', 'mark-connection':'CONNMARK', 'mark-packet':'MARK', 'mark-routing':'MARK (routing)', 'change-dscp':'DSCP', 'change-mss':'TCPMSS', 'change-ttl':'TTL / HL', 'set-priority':'CLASSIFY', 'passthrough':'COUNT / continue', 'jump':'JUMP'})[name] || name.toUpperCase();
- }
- function renderRuleFlag(disabled, hasComment) {
- let flags = '';
- if (disabled) flags += '<span class="text-rose-400 font-bold" title="Disabled">X</span>';
- if (hasComment) flags += '<span class="text-amber-400 font-bold ml-1" title="Has Comment">C</span>';
- return flags || '<span class="text-slate-600">-</span>';
- }
- function renderActionBadge(action) {
- const act = (action || '').toLowerCase();
- let color = 'bg-slate-800 text-slate-300';
- if (act === 'accept') color = 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30';
- else if (act === 'drop' || act === 'reject') color = 'bg-rose-500/20 text-rose-300 border border-rose-500/30';
- else if (act === 'masquerade' || act === 'src-nat' || act === 'dst-nat') color = 'bg-amber-500/20 text-amber-300 border border-amber-500/30';
- else if (act.startsWith('mark-')) color = 'bg-purple-500/20 text-purple-300 border border-purple-500/30';
- else if (act === 'log') color = 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30';
- return `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold ${color}">${escapeHtml(nativeFirewallTarget(action))}</span>`;
- }
- function switchFWSubTab(tab) {
- state.fwSubTab = tab;
- const tabs = ['filter', 'nat', 'mangle', 'addrlist', 'geo', 'connections'];
- tabs.forEach(t => {
- const panel = document.getElementById(`fw-subtab-${t}`);
- const btn = document.getElementById(`fw-subtab-btn-${t}`);
- if (panel) {
- if (t === tab) panel.classList.remove('hidden');
- else panel.classList.add('hidden');
- }
- if (btn) {
- if (t === tab) {
- 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';
- } else {
- 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';
- }
- }
- });
- const addBtn = document.getElementById('fw-primary-add-btn');
- if (addBtn) {
- if (tab === 'filter') addBtn.innerHTML = '<span>+ Add Filter Rule</span>';
- else if (tab === 'nat') addBtn.innerHTML = '<span>+ Add NAT Rule</span>';
- else if (tab === 'mangle') addBtn.innerHTML = '<span>+ Add Mangle Rule</span>';
- else if (tab === 'addrlist') addBtn.innerHTML = '<span>+ Add Address List</span>';
- else if (tab === 'geo') addBtn.innerHTML = '<span>⚙️ Schedule Settings</span>';
- else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
- }
- if (tab === 'filter') renderFilterRules();
- else if (tab === 'nat') renderNATRules();
- else if (tab === 'mangle') renderMangleRules();
- else if (tab === 'addrlist') renderAddressLists();
- else if (tab === 'geo') loadGeoIP();
- else if (tab === 'connections') loadConnections();
- setTimeout(initTableSorting, 50);
- }
- function openCurrentFWModal() {
- if (state.fwSubTab === 'filter') openAddFilterModal();
- else if (state.fwSubTab === 'nat') openAddNATModal();
- else if (state.fwSubTab === 'mangle') openAddMangleModal();
- else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
- else if (state.fwSubTab === 'geo') openGeoIntervalModal();
- else if (state.fwSubTab === 'connections') loadConnections();
- }
- async function loadFirewall(populateDropdowns = true) {
- try {
- const [summaryRes, filterRes, natRes, mangleRes, addrlistRes, geoStatusRes, geoCountriesRes] = await Promise.all([
- fetch(`${API_BASE}/firewall/summary`),
- fetch(`${API_BASE}/firewall/filter`),
- fetch(`${API_BASE}/firewall/nat`),
- fetch(`${API_BASE}/firewall/mangle`),
- fetch(`${API_BASE}/firewall/address-lists`),
- fetch(`${API_BASE}/firewall/geoip/status`),
- fetch(`${API_BASE}/firewall/geoip/countries`)
- ]);
- if (summaryRes.ok) state.fwSummary = await summaryRes.json();
- const applyError = document.getElementById('fw-apply-error');
- if (applyError) {
- applyError.textContent = state.fwSummary?.last_error ? 'Firewall configuration was not applied: ' + state.fwSummary.last_error : '';
- applyError.classList.toggle('hidden', !state.fwSummary?.last_error);
- }
- if (filterRes.ok) state.filterRules = await filterRes.json();
- if (natRes.ok) state.natRules = await natRes.json();
- if (mangleRes.ok) state.mangleRules = await mangleRes.json();
- if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
- if (geoStatusRes.ok) state.geoStatus = await geoStatusRes.json();
- if (geoCountriesRes.ok) state.geoCountries = await geoCountriesRes.json();
- if (applyError) { const messages=[state.fwSummary?.last_error, state.fwSummary?.connections_error, state.geoStatus?.last_error && 'GeoIP: '+state.geoStatus.last_error].filter(Boolean); applyError.textContent=messages.join(' · '); applyError.classList.toggle('hidden', !messages.length); }
- // Badges
- const bFilter = document.getElementById('fw-badge-filter');
- if (bFilter) bFilter.innerText = (state.filterRules || []).length;
- const bNat = document.getElementById('fw-badge-nat');
- if (bNat) bNat.innerText = (state.natRules || []).length;
- const bMangle = document.getElementById('fw-badge-mangle');
- if (bMangle) bMangle.innerText = (state.mangleRules || []).length;
- const bAddr = document.getElementById('fw-badge-addrlist');
- if (bAddr) bAddr.innerText = (state.addressLists || []).length;
- const bGeo = document.getElementById('fw-badge-geo');
- if (bGeo) bGeo.innerText = state.geoStatus?.enabled_count || 0;
- const sigFilter = (state.filterRules || []).map(r => JSON.stringify({...r, packets: 0, bytes: 0})).join(';');
- const sigNat = (state.natRules || []).map(r => JSON.stringify({...r, packets: 0, bytes: 0})).join(';');
- const sigMangle = (state.mangleRules || []).map(r => JSON.stringify({...r, packets: 0, bytes: 0})).join(';');
- const sigAddr = (state.addressLists || []).map(a => JSON.stringify(a)).join(';');
- const tbodyFilter = document.getElementById('filter-table-body');
- if (tbodyFilter) {
- if (populateDropdowns || tbodyFilter.dataset.sig !== sigFilter) {
- tbodyFilter.dataset.sig = sigFilter;
- renderFilterRules();
- } else {
- // In-place live stats update (ZERO flicker)
- (state.filterRules || []).forEach(r => {
- const p = document.getElementById(`filter-pkts-${r.id}`);
- if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
- const b = document.getElementById(`filter-bytes-${r.id}`);
- if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
- });
- }
- }
- const tbodyNat = document.getElementById('nat-table-body');
- if (tbodyNat) {
- if (populateDropdowns || tbodyNat.dataset.sig !== sigNat) {
- tbodyNat.dataset.sig = sigNat;
- renderNATRules();
- } else {
- (state.natRules || []).forEach(r => {
- const p = document.getElementById(`nat-pkts-${r.id}`);
- if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
- const b = document.getElementById(`nat-bytes-${r.id}`);
- if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
- });
- }
- }
- const tbodyMangle = document.getElementById('mangle-table-body');
- if (tbodyMangle) {
- if (populateDropdowns || tbodyMangle.dataset.sig !== sigMangle) {
- tbodyMangle.dataset.sig = sigMangle;
- renderMangleRules();
- } else {
- (state.mangleRules || []).forEach(r => {
- const p = document.getElementById(`mangle-pkts-${r.id}`);
- if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
- const b = document.getElementById(`mangle-bytes-${r.id}`);
- if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
- });
- }
- }
- const tbodyAddr = document.getElementById('addrlist-table-body');
- if (tbodyAddr && (populateDropdowns || tbodyAddr.dataset.sig !== sigAddr)) {
- tbodyAddr.dataset.sig = sigAddr;
- renderAddressLists();
- }
- renderGeoCountries();
- if (state.fwSubTab === 'connections') {
- loadConnections();
- }
- } catch (err) {
- console.error('Failed to load firewall:', err);
- }
- }
- // ----------------- Filter Rules -----------------
- function renderFilterRules() {
- const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
- const tbody = document.getElementById('filter-table-body');
- const empty = document.getElementById('filter-empty');
- if (!tbody) return;
- tbody.innerHTML = '';
- const rules = (state.filterRules || []).filter(r => !chainFilter || (r.chain || '').toLowerCase() === chainFilter);
- document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
- if (rules.length === 0) {
- empty?.classList.remove('hidden');
- return;
- }
- empty?.classList.add('hidden');
- rules.forEach((raw, idx) => {
- const r = safeFirewallRow(raw);
- const tr = document.createElement('tr');
- tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
- const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
- const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
- let actionExtra = '';
- if (r.action === 'reject') {
- actionExtra = `<span class="block text-[10px] text-rose-300 font-mono mt-0.5">(${r.reject_with || 'icmp-net-unreach'})</span>`;
- } else if (r.action === 'jump') {
- actionExtra = `<span class="block text-[10px] text-yellow-300 font-mono mt-0.5">→ ${r.jump_target || '-'}</span>`;
- } else if (r.action.includes('address-list') || r.action.includes('address list')) {
- actionExtra = `<span class="block text-[10px] text-emerald-300 font-mono mt-0.5">→ ${r.address_list || '-'}</span>`;
- } else if (r.action === 'log' && r.log_prefix) {
- actionExtra = `<span class="block text-[10px] text-slate-400 font-mono mt-0.5">${r.log_prefix}</span>`;
- }
- tr.innerHTML = `
- <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
- <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
- <td class="py-2.5 px-3 font-bold text-white">${(r.chain || '').toUpperCase()}</td>
- <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
- <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
- <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'} <span class="text-[9px] text-slate-500">IPv${r.ip_version || 4}</span></td>
- <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
- <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
- <td class="py-2.5 px-3">${renderActionBadge(r.action)}${actionExtra}</td>
- <td class="py-2.5 px-3 text-[11px] text-slate-400">
- <span class="text-slate-300" id="filter-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
- <span class="text-slate-500" id="filter-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
- </td>
- <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
- <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
- <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
- <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
- <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>
- <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
- <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
- </td>
- `;
- tbody.appendChild(tr);
- });
- }
- function formatTarget(addr, list, geo) {
- const parts = [];
- if (addr) parts.push(`<span>${addr}</span>`);
- if (list) {
- const inv = list.startsWith('!') ? '!' : '';
- const clean = list.replace(/^!/, '');
- 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>`);
- }
- if (geo) {
- const inv = geo.startsWith('!') ? '!' : '';
- const clean = geo.replace(/^!/, '').replace(/^geo:/, '');
- 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>`);
- }
- if (parts.length === 0) return '<span class="text-slate-600">0.0.0.0/0</span>';
- return parts.join(' ');
- }
- function populateInterfaceSelect(selectId, currentVal = '') {
- const sel = document.getElementById(selectId);
- if (!sel) return;
- sel.innerHTML = '<option value="">(Any Interface)</option>';
- (state.interfaces || []).forEach(i => {
- const opt = document.createElement('option');
- opt.value = i.name;
- opt.innerText = `${i.name} (${i.role || i.type})`;
- if (i.name === currentVal) opt.selected = true;
- sel.appendChild(opt);
- });
- if (state.sdwanGroups && state.sdwanGroups.length > 0) {
- const optgroup = document.createElement('optgroup');
- optgroup.label = 'SD-WAN Groups';
- state.sdwanGroups.forEach(g => {
- const opt = document.createElement('option');
- opt.value = g.name;
- opt.innerText = `${g.name} [SD-WAN: ${g.mode}]`;
- if (g.name === currentVal) opt.selected = true;
- optgroup.appendChild(opt);
- });
- sel.appendChild(optgroup);
- }
- }
- function populateAddressListSelect(selectId, currentVal = '') {
- const sel = document.getElementById(selectId);
- if (!sel) return;
- sel.innerHTML = '<option value="">(None)</option>';
- const cleanVal = (currentVal || '').replace(/^!/, '');
- const ruleLists = [...(state.filterRules||[]), ...(state.natRules||[]), ...(state.mangleRules||[])].flatMap(r => [r.src_address_list,r.dst_address_list,r.address_list]).filter(Boolean).map(n => n.replace(/^!/, '')).filter(n => !n.startsWith('geo:') && !n.startsWith('geo_'));
- const customNames = Array.from(new Set([...(state.addressLists || []).map(a => a.name), ...ruleLists])).sort();
- customNames.forEach(name => {
- const count = (state.addressLists || []).filter(a => a.name === name).length;
- const opt = document.createElement('option');
- opt.value = name;
- opt.innerText = `${name} (${count} entries)`;
- if (name === cleanVal) opt.selected = true;
- sel.appendChild(opt);
- });
- if (cleanVal && !Array.from(sel.options).some(option => option.value === cleanVal)) {
- const opt = document.createElement('option');
- opt.value = cleanVal;
- opt.innerText = cleanVal;
- opt.selected = true;
- sel.appendChild(opt);
- }
- populateCommonAddrListDatalist();
- }
- function populateCommonAddrListDatalist() {
- const dl = document.getElementById('fw-addrlist-datalist');
- if (!dl) return;
- dl.innerHTML = '';
- const names = Array.from(new Set((state.addressLists || []).map(a => a.name).filter(Boolean))).sort();
- names.forEach(name => {
- const opt = document.createElement('option');
- opt.value = name;
- dl.appendChild(opt);
- });
- }
- function populateGeoIPSelect(selectId, currentVal = '') {
- const sel = document.getElementById(selectId);
- if (!sel) return;
- sel.innerHTML = '<option value="">(None)</option>';
- const cleanVal = (currentVal || '').replace(/^!/, '').replace(/^geo:/, '').toUpperCase();
- // Presets optgroup
- const grpPresets = document.createElement('optgroup');
- grpPresets.label = '⚡ Regional Presets';
- const presets = [
- { code: 'EU', label: '🇪🇺 European Union (EU - 27 countries)' },
- { code: 'BALKANS', label: '🏛️ Balkans (GR, CY, BG, RO, AL, etc.)' },
- { code: 'BLOCKLIST', label: '🛡️ High-Risk Blocklist (CN, RU, IR, KP, BY)' }
- ];
- presets.forEach(p => {
- const opt = document.createElement('option');
- opt.value = p.code;
- opt.innerText = p.label;
- if (p.code === cleanVal) opt.selected = true;
- grpPresets.appendChild(opt);
- });
- sel.appendChild(grpPresets);
- // All Countries optgroup
- const grpCountries = document.createElement('optgroup');
- grpCountries.label = '🌍 All Countries';
- const countries = (state.geoCountries || []).slice().sort((a, b) => a.name.localeCompare(b.name));
- countries.forEach(c => {
- const opt = document.createElement('option');
- opt.value = c.code;
- const subnetsInfo = c.subnet_count ? ` [${c.subnet_count.toLocaleString()} subnets]` : '';
- opt.innerText = `${c.name} (${c.code})${subnetsInfo}`;
- if (c.code === cleanVal) opt.selected = true;
- grpCountries.appendChild(opt);
- });
- sel.appendChild(grpCountries);
- }
- // ==================== FIREWALL FILTER MODAL (DEBTIK WEBFIG / WINBOX V4) ====================
- function switchFwRuleTab(tab) {
- state.activeFwRuleTab = tab;
- document.querySelectorAll('.fw-rule-tab-btn').forEach(btn => {
- btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
- btn.classList.add('text-slate-400', 'border-transparent');
- });
- const activeBtn = document.getElementById(`fw-tab-btn-${tab}`);
- if (activeBtn) {
- activeBtn.classList.remove('text-slate-400', 'border-transparent');
- activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
- }
- document.querySelectorAll('.fw-rule-pane').forEach(p => p.classList.add('hidden'));
- const activePane = document.getElementById(`fw-pane-${tab}`);
- if (activePane) activePane.classList.remove('hidden');
- if (tab === 'statistics') {
- startFwStatPolling();
- } else {
- stopFwStatPolling();
- }
- }
- function toggleFwField(fieldKey, expand) {
- const plusBtn = document.getElementById(`fw-plus-${fieldKey}`);
- const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
- if (!plusBtn || !fieldBox) return;
- if (expand) {
- plusBtn.classList.add('hidden');
- fieldBox.classList.remove('hidden');
- const valInput = document.getElementById(`fw-val-${fieldKey}`);
- if (valInput) valInput.focus();
- } else {
- fieldBox.classList.add('hidden');
- plusBtn.classList.remove('hidden');
- const valInput = document.getElementById(`fw-val-${fieldKey}`);
- if (valInput) {
- if (valInput.tagName === 'SELECT') {
- valInput.selectedIndex = 0;
- } else {
- valInput.value = '';
- }
- }
- const invInput = document.getElementById(`fw-inv-${fieldKey}`);
- if (invInput) invInput.checked = false;
- if (fieldKey === 'cs') {
- ['filter-modal-cs-established', 'filter-modal-cs-related', 'filter-modal-cs-new', 'filter-modal-cs-invalid', 'filter-modal-cs-untracked'].forEach(id => {
- const el = document.getElementById(id);
- if (el) el.checked = false;
- });
- }
- if (fieldKey === 'natstate') {
- ['filter-modal-nat-srcnat', 'filter-modal-nat-dstnat'].forEach(id => {
- const el = document.getElementById(id);
- if (el) el.checked = false;
- });
- }
- if (fieldKey === 'days') {
- ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
- const el = document.getElementById(`fw-day-${d}`);
- if (el) el.checked = true;
- });
- }
- }
- }
- function setFwFieldVal(fieldKey, value, hasInvert = false) {
- if (fieldKey === 'ipsec' && typeof value === 'string') value = value.replace(':', ',');
- if (value !== undefined && value !== null && value !== '' && !(fieldKey === 'proto' && value === 'all')) {
- toggleFwField(fieldKey, true);
- let strVal = String(value);
- if (hasInvert) {
- const inv = strVal.startsWith('!');
- if (inv) strVal = strVal.slice(1);
- const invEl = document.getElementById(`fw-inv-${fieldKey}`);
- if (invEl) invEl.checked = inv;
- else if (inv) strVal = '!'+strVal;
- }
- const valEl = document.getElementById(`fw-val-${fieldKey}`);
- if (valEl) { if (valEl.tagName === 'SELECT' && !Array.from(valEl.options).some(o => o.value === strVal)) { const option=document.createElement('option'); option.value=strVal; option.textContent=strVal+' (saved)'; valEl.appendChild(option); } valEl.value = strVal; }
- } else {
- toggleFwField(fieldKey, false);
- }
- }
- function getFwFieldVal(fieldKey, hasInvert = false) {
- const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
- if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
- const valEl = document.getElementById(`fw-val-${fieldKey}`);
- let v = valEl ? valEl.value.trim() : '';
- if (!v) return '';
- if (hasInvert) {
- const invEl = document.getElementById(`fw-inv-${fieldKey}`);
- if (invEl && invEl.checked) {
- v = '!' + v.replace(/^!/, '');
- }
- }
- return v;
- }
- function toggleMaximizeFilterModal() {
- const win = document.getElementById('filter-modal-window');
- if (!win) return;
- if (win.classList.contains('max-w-[720px]')) {
- win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
- win.classList.add('max-w-[96vw]', 'h-[94vh]');
- } else {
- win.classList.remove('max-w-[96vw]', 'h-[94vh]');
- win.classList.add('max-w-[720px]', 'max-h-[92vh]');
- }
- }
- const FW_NATIVE_CHAINS = {
- filter: [
- { id: 'forward', label: 'FORWARD (routed through router)' },
- { id: 'input', label: 'INPUT (destined to this router)' },
- { id: 'output', label: 'OUTPUT (generated by this router)' }
- ],
- nat: [
- { id: 'postrouting', label: 'POSTROUTING (outgoing after routing — SNAT / MASQUERADE)' },
- { id: 'prerouting', label: 'PREROUTING (incoming before routing — DNAT / REDIRECT)' },
- { id: 'output', label: 'OUTPUT (locally generated — DNAT / REDIRECT)' },
- { id: 'input', label: 'INPUT (destined to this machine — SNAT)' }
- ],
- mangle: [
- { id: 'prerouting', label: 'PREROUTING (incoming before routing)' },
- { id: 'input', label: 'INPUT (destined to this machine)' },
- { id: 'forward', label: 'FORWARD (routed through router)' },
- { id: 'output', label: 'OUTPUT (generated by this machine)' },
- { id: 'postrouting', label: 'POSTROUTING (outgoing after routing)' }
- ]
- };
- function populateChainDropdown(table, currentChain) {
- const sel = document.getElementById(`${table}-modal-chain-select`);
- if (!sel) return;
- const cur = (currentChain || '').trim();
- const lower = cur.toLowerCase();
- const rulesKey = table === 'filter' ? 'filterRules' : table === 'nat' ? 'natRules' : 'mangleRules';
- const rules = state[rulesKey] || [];
- const nativeIds = FW_NATIVE_CHAINS[table].map(c => c.id);
- const customChains = new Set();
- rules.forEach(r => {
- if (r.chain) {
- const c = r.chain.trim();
- const l = c.toLowerCase();
- if (!nativeIds.includes(l) && l !== 'srcnat' && l !== 'dstnat' && !['forward', 'input', 'output', 'prerouting', 'postrouting'].includes(l)) {
- customChains.add(c);
- }
- }
- });
- const isCurrentCustom = cur && !nativeIds.includes(lower) && lower !== 'srcnat' && lower !== 'dstnat' && !['forward', 'input', 'output', 'prerouting', 'postrouting'].includes(lower);
- if (isCurrentCustom) {
- customChains.add(cur);
- }
- let html = '';
- FW_NATIVE_CHAINS[table].forEach(c => {
- html += `<option value="${c.id}">${escapeHtml(c.label)}</option>`;
- });
- if (customChains.size > 0) {
- html += `<optgroup label="Custom Chains">`;
- customChains.forEach(c => {
- html += `<option value="${escapeHtml(c)}">Chain: ${escapeHtml(c)} (custom)</option>`;
- });
- html += `</optgroup>`;
- }
- html += `<option value="__custom__">+ Custom Chain...</option>`;
- sel.innerHTML = html;
- if (isCurrentCustom) {
- sel.value = cur;
- } else if (nativeIds.includes(lower)) {
- sel.value = lower;
- } else if (table === 'nat' && (lower === 'srcnat' || lower === 'dstnat')) {
- sel.value = lower === 'dstnat' ? 'prerouting' : 'postrouting';
- } else {
- sel.value = nativeIds[0];
- }
- const customWrap = document.getElementById(`${table}-modal-custom-wrap`);
- const customInput = document.getElementById(`${table}-modal-custom-input`);
- if (isCurrentCustom || sel.value === '__custom__') {
- if (customWrap) customWrap.classList.remove('hidden');
- if (customInput) customInput.value = cur;
- } else {
- if (customWrap) customWrap.classList.add('hidden');
- if (customInput) customInput.value = '';
- }
- const chainInput = document.getElementById(`${table}-modal-chain`);
- if (chainInput) chainInput.value = cur || sel.value;
- }
- function syncFilterChainFromSelect() {
- const sel = document.getElementById('filter-modal-chain-select');
- const customWrap = document.getElementById('filter-modal-custom-wrap');
- const customInput = document.getElementById('filter-modal-custom-input');
- const chainInput = document.getElementById('filter-modal-chain');
- if (!sel || !chainInput) return;
- if (sel.value === '__custom__') {
- if (customWrap) customWrap.classList.remove('hidden');
- if (customInput) {
- customInput.value = '';
- customInput.focus();
- }
- chainInput.value = '';
- } else {
- if (customWrap) customWrap.classList.add('hidden');
- chainInput.value = sel.value;
- }
- handleFilterChainChange();
- }
- function syncFilterCustomChainInput() {
- const customInput = document.getElementById('filter-modal-custom-input');
- const chainInput = document.getElementById('filter-modal-chain');
- if (customInput && chainInput) {
- chainInput.value = customInput.value.trim();
- }
- handleFilterChainChange();
- }
- function handleFilterChainChange() {
- const chainInput = document.getElementById('filter-modal-chain');
- const chain = (chainInput?.value || 'forward').trim().toLowerCase();
- const sel = document.getElementById('filter-modal-chain-select');
- if (sel && sel.value !== chain && sel.value !== '__custom__') {
- if (['forward', 'input', 'output'].includes(chain)) {
- sel.value = chain;
- }
- }
- const hintEl = document.getElementById('filter-chain-hint');
- if (hintEl) {
- if (chain === 'forward') {
- hintEl.textContent = 'FORWARD: packets routed through this router (accepts both In and Out interfaces).';
- } else if (chain === 'input') {
- hintEl.textContent = 'INPUT: packets destined to this router (In-Interface only; Out-Interface is invalid in iptables).';
- } else if (chain === 'output') {
- hintEl.textContent = 'OUTPUT: packets generated by this router (Out-Interface only; In-Interface is invalid in iptables).';
- } else {
- hintEl.textContent = `Custom chain "${chain}": reached via an explicit JUMP from a built-in chain.`;
- }
- }
- const rowIn = document.getElementById('fw-row-iniface');
- const rowInList = document.getElementById('fw-row-inifacelist');
- const rowOut = document.getElementById('fw-row-outiface');
- const rowOutList = document.getElementById('fw-row-outifacelist');
- const rowInBridge = document.getElementById('fw-row-inbridgeport');
- const rowOutBridge = document.getElementById('fw-row-outbridgeport');
- const rowSrcMac = document.getElementById('fw-row-srcmac');
- if (chain === 'input') {
- if (rowIn) rowIn.classList.remove('hidden');
- if (rowInList) rowInList.classList.remove('hidden');
- if (rowOut) rowOut.classList.add('hidden');
- if (rowOutList) rowOutList.classList.add('hidden');
- if (rowInBridge) rowInBridge.classList.remove('hidden');
- if (rowOutBridge) rowOutBridge.classList.add('hidden');
- if (rowSrcMac) rowSrcMac.classList.remove('hidden');
- } else if (chain === 'output') {
- if (rowIn) rowIn.classList.add('hidden');
- if (rowInList) rowInList.classList.add('hidden');
- if (rowOut) rowOut.classList.remove('hidden');
- if (rowOutList) rowOutList.classList.remove('hidden');
- if (rowInBridge) rowInBridge.classList.add('hidden');
- if (rowOutBridge) rowOutBridge.classList.remove('hidden');
- if (rowSrcMac) rowSrcMac.classList.add('hidden');
- } else {
- if (rowIn) rowIn.classList.remove('hidden');
- if (rowInList) rowInList.classList.remove('hidden');
- if (rowOut) rowOut.classList.remove('hidden');
- if (rowOutList) rowOutList.classList.remove('hidden');
- if (rowInBridge) rowInBridge.classList.remove('hidden');
- if (rowOutBridge) rowOutBridge.classList.remove('hidden');
- if (rowSrcMac) rowSrcMac.classList.remove('hidden');
- }
- checkFilterActionChainCompatibility();
- }
- function checkFilterActionChainCompatibility() {
- const chain = (document.getElementById('filter-modal-chain')?.value || 'forward').trim().toLowerCase();
- const warnBox = document.getElementById('filter-action-incompatible-warn');
- const warnMsg = document.getElementById('filter-action-incompatible-msg');
- if (!warnBox || !warnMsg) return;
- if (chain === 'prerouting' || chain === 'postrouting') {
- warnMsg.textContent = `Chain "${chain.toUpperCase()}" is not available in the Filter table. Filter only supports INPUT, FORWARD, OUTPUT or custom chains.`;
- warnBox.classList.remove('hidden');
- } else {
- warnBox.classList.add('hidden');
- }
- }
- function openAddFilterModal() {
- const tos = document.getElementById('fw-val-tos'); if (tos) tos.value = '';
- switchFwRuleTab('general');
- setFirewallDays('fw', '');
- const badge = document.getElementById('fw-modal-badge');
- if (badge) badge.innerText = 'New...';
- document.getElementById('filter-modal-id').value = '';
- document.getElementById('filter-modal-family').value = '4';
- document.getElementById('filter-modal-enabled').checked = true;
- document.getElementById('filter-modal-comment').value = '';
- document.getElementById('filter-modal-chain').value = 'forward';
- populateChainDropdown('filter', 'forward');
- handleFilterChainChange();
- document.getElementById('filter-modal-action').value = 'accept';
- document.getElementById('filter-modal-log').checked = false;
- populateInterfaceSelect('fw-val-iniface');
- populateInterfaceSelect('fw-val-outiface');
- populateAddressListSelect('fw-val-srclist');
- populateAddressListSelect('fw-val-dstlist');
- populateGeoIPSelect('fw-val-srcgeo');
- populateGeoIPSelect('fw-val-dstgeo');
- const allFieldKeys = [
- 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
- 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
- 'routingmark', 'conntype', 'cs', 'natstate',
- 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
- 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
- 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
- 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
- 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
- ];
- allFieldKeys.forEach(k => toggleFwField(k, false));
- resetRuleCounterDisplay();
- toggleFilterActionFields();
- refreshFirewallRejectTypes();
- document.getElementById('filter-modal').classList.remove('hidden');
- }
- function openEditFilterModal(id) {
- id = decodeURIComponent(id);
- const r = (state.filterRules || []).find(rule => rule.id === id);
- if (!r) return;
- switchFwRuleTab('general');
- const badge = document.getElementById('fw-modal-badge');
- if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
- document.getElementById('filter-modal-id').value = r.id;
- document.getElementById('filter-modal-family').value = String(r.ip_version || 4);
- document.getElementById('filter-modal-enabled').checked = !r.disabled;
- document.getElementById('filter-modal-comment').value = r.comment || '';
- const filterChain = r.chain || 'forward';
- document.getElementById('filter-modal-chain').value = filterChain;
- populateChainDropdown('filter', filterChain);
- handleFilterChainChange();
- setFirewallActionSelection('filter', r.action || 'accept');
- document.getElementById('filter-modal-log').checked = !!r.log;
- populateInterfaceSelect('fw-val-iniface', (r.in_interface || '').replace(/^!/, ''));
- populateInterfaceSelect('fw-val-outiface', (r.out_interface || '').replace(/^!/, ''));
- populateAddressListSelect('fw-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
- populateAddressListSelect('fw-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
- populateGeoIPSelect('fw-val-srcgeo', r.src_geoip || '');
- populateGeoIPSelect('fw-val-dstgeo', r.dst_geoip || '');
- setFwFieldVal('src', r.src_address, true);
- setFwFieldVal('dst', r.dst_address, true);
- setFwFieldVal('srclist', r.src_address_list, true);
- setFwFieldVal('dstlist', r.dst_address_list, true);
- setFwFieldVal('srcgeo', r.src_geoip, true);
- setFwFieldVal('dstgeo', r.dst_geoip, true);
- if (r.protocol && r.protocol !== 'all') {
- setFwFieldVal('proto', r.protocol, true);
- } else {
- toggleFwField('proto', false);
- }
- setFwFieldVal('sport', r.src_port, true);
- setFwFieldVal('dport', r.dst_port, true);
- setFwFieldVal('anyport', r.any_port, true);
- setFwFieldVal('iniface', r.in_interface, true);
- setFwFieldVal('outiface', r.out_interface, true);
- setFwFieldVal('inifacelist', r.in_interface_list, true);
- setFwFieldVal('outifacelist', r.out_interface_list, true);
- setFwFieldVal('pktmark', r.packet_mark, true);
- setFwFieldVal('connmark', r.connection_mark, true);
- setFwFieldVal('routingmark', r.routing_mark, true);
- setFwFieldVal('conntype', r.connection_type, false);
- const states = r.connection_state || [];
- if (states.length > 0) {
- toggleFwField('cs', true);
- document.getElementById('filter-modal-cs-established').checked = states.includes('established');
- document.getElementById('filter-modal-cs-related').checked = states.includes('related');
- document.getElementById('filter-modal-cs-new').checked = states.includes('new');
- document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
- document.getElementById('filter-modal-cs-untracked').checked = states.includes('untracked');
- } else {
- toggleFwField('cs', false);
- }
- const natStates = r.connection_nat_state || [];
- if (natStates.length > 0) {
- toggleFwField('natstate', true);
- document.getElementById('filter-modal-nat-srcnat').checked = natStates.includes('srcnat');
- document.getElementById('filter-modal-nat-dstnat').checked = natStates.includes('dstnat');
- } else {
- toggleFwField('natstate', false);
- }
- // Advanced tab fields
- setFwFieldVal('layer7', r.layer7_protocol, false);
- setFwFieldVal('content', r.content, false);
- setFwFieldVal('connbytes', r.connection_bytes, false);
- setFwFieldVal('connrate', r.connection_rate, false);
- setFwFieldVal('pcc', r.pcc, false);
- setFwFieldVal('srcmac', r.src_mac_address, true);
- setFwFieldVal('outbridgeport', r.out_bridge_port, false);
- setFwFieldVal('inbridgeport', r.in_bridge_port, false);
- setFwFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
- setFwFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
- setFwFieldVal('ipsec', r.ipsec_policy, false);
- setFwFieldVal('tlshost', r.tls_host, false);
- setFwFieldVal('ingresspriority', r.ingress_priority, false);
- setFwFieldVal('priority', r.priority, false);
- setFwFieldVal('dscp', r.dscp, false);
- setFwFieldVal('tcpmss', r.tcp_mss, false);
- { const tosEl = document.getElementById('fw-val-tos'); if (tosEl) tosEl.value = r.tos || ''; }
- setFwFieldVal('pktsize', r.packet_size, false);
- setFwFieldVal('random', r.random, false);
- setFwFieldVal('tcpflags', r.tcp_flags, false);
- setFwFieldVal('icmpoptions', r.icmp_options, false);
- setFwFieldVal('ipv4options', r.ipv4_options, false);
- setFwFieldVal('ttl', r.ttl, false);
- // Extra tab fields
- setFwFieldVal('time', r.time, false);
- if (r.days) {
- toggleFwField('days', true);
- ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
- const chk = document.getElementById(`fw-day-${d}`);
- if (chk) chk.checked = r.days.toLowerCase().includes(d);
- });
- } else {
- toggleFwField('days', false);
- }
- setFwFieldVal('limit', r.limit, false);
- setFwFieldVal('dstlimit', r.dst_limit, false);
- setFwFieldVal('psd', r.psd, false);
- // Action fields
- if (r.reject_with) {
- const rwEl = document.getElementById('filter-modal-rejectwith');
- if (rwEl) rwEl.value = r.reject_with;
- }
- if (r.jump_target) {
- const jtEl = document.getElementById('filter-modal-jumptarget');
- if (jtEl) jtEl.value = r.jump_target;
- }
- if (r.address_list) {
- const alEl = document.getElementById('filter-modal-action-addrlist');
- if (alEl) alEl.value = r.address_list;
- }
- if (r.address_list_timeout) {
- const toEl = document.getElementById('filter-modal-action-timeout');
- if (toEl) toEl.value = r.address_list_timeout;
- }
- setFwFieldVal('logprefix', r.log_prefix, false);
- // Statistics
- const bEl = document.getElementById('fw-stat-bytes');
- const pEl = document.getElementById('fw-stat-packets');
- if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
- if (pEl) pEl.value = (r.packets || 0).toLocaleString();
- state.fwLastBytes = r.bytes || 0;
- state.fwLastPackets = r.packets || 0;
- state.fwLastTimestamp = Date.now();
- state.fwStatRateHistory = new Array(30).fill(0);
- state.fwStatPktHistory = new Array(30).fill(0);
- renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
- renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
- toggleFilterActionFields();
- refreshFirewallRejectTypes();
- document.getElementById('filter-modal').classList.remove('hidden');
- }
- function closeFilterModal() {
- stopFwStatPolling();
- document.getElementById('filter-modal').classList.add('hidden');
- }
- function toggleFilterActionFields() {
- const act = document.getElementById('filter-modal-action')?.value || 'accept';
- const rejectBox = document.getElementById('filter-action-reject-box');
- const jumpBox = document.getElementById('filter-action-jump-box');
- const addrBox = document.getElementById('filter-action-addrlist-box');
- if (rejectBox) {
- if (act === 'reject') rejectBox.classList.remove('hidden');
- else rejectBox.classList.add('hidden');
- }
- if (jumpBox) {
- if (act === 'jump') jumpBox.classList.remove('hidden');
- else jumpBox.classList.add('hidden');
- }
- if (addrBox) {
- if (act === 'add-dst-to-address-list' || act === 'add-src-to-address-list' || act.includes('address-list') || act.includes('address list')) {
- addrBox.classList.remove('hidden');
- } else {
- addrBox.classList.add('hidden');
- }
- }
- if (act === 'log') {
- const logEl = document.getElementById('filter-modal-log');
- if (logEl) logEl.checked = true;
- toggleFwField('logprefix', true);
- }
- }
- function toggleFwLogPrefix() {
- const isLog = document.getElementById('filter-modal-log')?.checked;
- toggleFwField('logprefix', !!isLog);
- }
- function copyFilterRule() {
- document.getElementById('filter-modal-id').value = '';
- const badge = document.getElementById('fw-modal-badge');
- if (badge) badge.innerText = 'New...';
- showToast('Rule Cloned', 'Ready to save as a new rule copy', 'info');
- }
- function resetRuleCounterDisplay() {
- state.fwStatRateHistory = new Array(30).fill(0);
- state.fwStatPktHistory = new Array(30).fill(0);
- state.fwLastBytes = 0;
- state.fwLastPackets = 0;
- state.fwLastTimestamp = Date.now();
- const bEl = document.getElementById('fw-stat-bytes');
- const pEl = document.getElementById('fw-stat-packets');
- const rEl = document.getElementById('fw-stat-rate');
- const prEl = document.getElementById('fw-stat-pktrate');
- if (bEl) bEl.value = '0 B';
- if (pEl) pEl.value = '0';
- if (rEl) rEl.value = '0 bps';
- if (prEl) prEl.value = '0 p/s';
- renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
- renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
- showToast('Counters Reset', 'Rule counter display reset to 0', 'info');
- }
- async function resetAllFwCounters() {
- try {
- const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
- if (res.ok) {
- resetRuleCounterDisplay();
- showToast('All Counters Reset', 'All firewall counters zeroed', 'success');
- loadFirewall(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function applyFilterRule(closeAfter = false) {
- const id = document.getElementById('filter-modal-id').value;
- if (!reviewLegacyFirewallSettings('filter', id)) return;
- let selectedDays; try { selectedDays = getFirewallDays('fw'); } catch(error) { showToast('Error', error.message, 'error'); return; }
- const chain = (document.getElementById('filter-modal-chain').value || '').trim();
- const chainLower = chain.toLowerCase();
- if (!chain) { switchFwRuleTab('general'); showToast('Filter Rule', 'A valid chain is required.', 'error'); document.getElementById('filter-modal-chain').focus(); return; }
- if (chainLower === 'prerouting' || chainLower === 'postrouting') {
- switchFwRuleTab('general');
- showToast('Invalid Chain', `Chain "${chain.toUpperCase()}" is not available in the Filter table in iptables.`, 'error');
- return;
- }
- const action = document.getElementById('filter-modal-action').value;
- const comment = document.getElementById('filter-modal-comment').value.trim();
- const enabled = document.getElementById('filter-modal-enabled').checked;
- const src = getFwFieldVal('src', true);
- const dst = getFwFieldVal('dst', true);
- const srclist = getFwFieldVal('srclist', true);
- const dstlist = getFwFieldVal('dstlist', true);
- const srcgeo = getFwFieldVal('srcgeo', true);
- const dstgeo = getFwFieldVal('dstgeo', true);
- const proto = getFwFieldVal('proto', true);
- const sport = getFwFieldVal('sport', true);
- const dport = getFwFieldVal('dport', true);
- const anyport = getFwFieldVal('anyport', true);
- if ((sport || dport || anyport) && !['tcp', 'udp'].includes(proto)) {
- switchFwRuleTab('general'); toggleFwField('proto', true);
- showToast('Select protocol', 'Port matches require TCP or UDP without protocol inversion.', 'error'); document.getElementById('fw-val-proto').focus(); return;
- }
- let iniface = getFwFieldVal('iniface', true);
- let outiface = getFwFieldVal('outiface', true);
- let inifacelist = getFwFieldVal('inifacelist', true);
- let outifacelist = getFwFieldVal('outifacelist', true);
- if (chainLower === 'input') {
- outiface = '';
- outifacelist = '';
- } else if (chainLower === 'output') {
- iniface = '';
- inifacelist = '';
- }
- const pktmark = getFwFieldVal('pktmark', true);
- const connmark = getFwFieldVal('connmark', true);
- const routingmark = getFwFieldVal('routingmark', true);
- const conntype = getFwFieldVal('conntype', false);
- const states = [];
- const csBox = document.getElementById('fw-field-cs');
- if (csBox && !csBox.classList.contains('hidden')) {
- if (document.getElementById('filter-modal-cs-established')?.checked) states.push('established');
- if (document.getElementById('filter-modal-cs-related')?.checked) states.push('related');
- if (document.getElementById('filter-modal-cs-new')?.checked) states.push('new');
- if (document.getElementById('filter-modal-cs-invalid')?.checked) states.push('invalid');
- if (document.getElementById('filter-modal-cs-untracked')?.checked) states.push('untracked');
- }
- const natStates = [];
- const natBox = document.getElementById('fw-field-natstate');
- if (natBox && !natBox.classList.contains('hidden')) {
- if (document.getElementById('filter-modal-nat-srcnat')?.checked) natStates.push('srcnat');
- if (document.getElementById('filter-modal-nat-dstnat')?.checked) natStates.push('dstnat');
- }
- const payload = {
- ip_version: Number(document.getElementById('filter-modal-family').value),
- id,
- chain,
- action,
- protocol: proto || 'all',
- src_address: src,
- dst_address: dst,
- src_port: sport,
- dst_port: dport,
- any_port: anyport,
- in_interface: iniface,
- out_interface: outiface,
- in_interface_list: inifacelist,
- out_interface_list: outifacelist,
- packet_mark: pktmark,
- connection_mark: connmark,
- routing_mark: routingmark,
- connection_type: conntype,
- connection_state: states,
- connection_nat_state: natStates,
- src_address_list: srclist,
- dst_address_list: dstlist,
- src_geoip: srcgeo,
- dst_geoip: dstgeo,
- comment,
- disabled: !enabled,
- // Advanced tab
- content: getFwFieldVal('content', false),
- src_mac_address: chainLower === 'output' ? '' : getFwFieldVal('srcmac', true),
- out_bridge_port: chainLower === 'input' ? '' : getFwFieldVal('outbridgeport', false),
- in_bridge_port: chainLower === 'output' ? '' : getFwFieldVal('inbridgeport', false),
- ipsec_policy: getFwFieldVal('ipsec', false),
- dscp: getFwFieldVal('dscp', false),
- tcp_mss: getFwFieldVal('tcpmss', false),
- tos: document.getElementById('fw-val-tos')?.value || '',
- packet_size: getFwFieldVal('pktsize', false),
- random: getFwFieldVal('random', false),
- tcp_flags: getFwFieldVal('tcpflags', false),
- icmp_options: getFwFieldVal('icmpoptions', false),
- ttl: getFwFieldVal('ttl', false),
- days: selectedDays,
- // Extra tab
- time: getFwFieldVal('time', false),
- limit: getFwFieldVal('limit', false),
- // Action tab
- reject_with: action === 'reject' ? (document.getElementById('filter-modal-rejectwith')?.value || '') : '',
- jump_target: action === 'jump' ? (document.getElementById('filter-modal-jumptarget')?.value || '') : '',
- address_list: action.startsWith('add-') ? (document.getElementById('filter-modal-action-addrlist')?.value || '') : '',
- address_list_timeout: action.startsWith('add-') ? (document.getElementById('filter-modal-action-timeout')?.value || '') : '',
- log: document.getElementById('filter-modal-log')?.checked || false,
- log_prefix: getFwFieldVal('logprefix', false)
- };
- try {
- const res = await fetch(`${API_BASE}/firewall/filter`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(payload)
- });
- if (res.ok) {
- const data = await res.json();
- showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
- loadFirewall(false);
- if (closeAfter) {
- closeFilterModal();
- } else {
- if (data.id) {
- document.getElementById('filter-modal-id').value = data.id;
- const badge = document.getElementById('fw-modal-badge');
- if (badge) badge.innerText = `#${data.id}`;
- }
- }
- } else {
- const err = await res.json();
- showToast('Error', err.message || 'Failed to save rule', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- function submitSaveFilterRule(e) {
- if (e && e.preventDefault) e.preventDefault();
- return applyFilterRule(true);
- }
- function startFwStatPolling() {
- stopFwStatPolling();
- pollRuleStats();
- state.fwStatInterval = setInterval(pollRuleStats, 1000);
- }
- function stopFwStatPolling() {
- if (state.fwStatInterval) {
- clearInterval(state.fwStatInterval);
- state.fwStatInterval = null;
- }
- }
- async function pollRuleStats() {
- const id = document.getElementById('filter-modal-id')?.value;
- if (!id) {
- renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory || new Array(30).fill(0), 'bps', 'fw-stat-legend-rate');
- renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory || new Array(30).fill(0), 'p/s', 'fw-stat-legend-pktrate');
- return;
- }
- try {
- const res = await fetch(`${API_BASE}/firewall/filter`);
- if (!res.ok) return;
- const rules = await res.json();
- const r = rules.find(x => x.id === id);
- if (!r) return;
- const now = Date.now();
- const dt = Math.max(0.2, (now - (state.fwLastTimestamp || now)) / 1000);
- state.fwLastTimestamp = now;
- const curBytes = r.bytes || 0;
- const curPackets = r.packets || 0;
- const deltaBytes = Math.max(0, curBytes - (state.fwLastBytes ?? curBytes));
- const deltaPkts = Math.max(0, curPackets - (state.fwLastPackets ?? curPackets));
- state.fwLastBytes = curBytes;
- state.fwLastPackets = curPackets;
- const rateBps = Math.round((deltaBytes * 8) / dt);
- const ratePkt = Math.round(deltaPkts / dt);
- if (!state.fwStatRateHistory) state.fwStatRateHistory = new Array(30).fill(0);
- if (!state.fwStatPktHistory) state.fwStatPktHistory = new Array(30).fill(0);
- state.fwStatRateHistory.push(rateBps);
- if (state.fwStatRateHistory.length > 30) state.fwStatRateHistory.shift();
- state.fwStatPktHistory.push(ratePkt);
- if (state.fwStatPktHistory.length > 30) state.fwStatPktHistory.shift();
- const bEl = document.getElementById('fw-stat-bytes');
- const pEl = document.getElementById('fw-stat-packets');
- const rEl = document.getElementById('fw-stat-rate');
- const prEl = document.getElementById('fw-stat-pktrate');
- if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
- if (pEl) pEl.value = curPackets.toLocaleString();
- if (rEl) rEl.value = formatBps(rateBps);
- if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
- renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
- renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
- } catch (e) {
- console.error('Error polling rule stats', e);
- }
- }
- function formatBps(bps) {
- if (bps >= 1000000000) return (bps / 1000000000).toFixed(1) + ' Gbps';
- if (bps >= 1000000) return (bps / 1000000).toFixed(1) + ' Mbps';
- if (bps >= 1000) return (bps / 1000).toFixed(1) + ' kbps';
- return bps + ' bps';
- }
- function renderFwSparkline(svgId, dataArray, unit, legendId) {
- const svg = document.getElementById(svgId);
- if (!svg) return;
- const w = 500;
- const h = 100;
- const paddingRight = 45;
- const graphWidth = w - paddingRight;
- const maxVal = Math.max(5, ...dataArray);
- const currentVal = dataArray[dataArray.length - 1] || 0;
- const leg = document.getElementById(legendId);
- if (leg) {
- leg.innerText = unit === 'bps' ? formatBps(currentVal) : `${currentVal.toLocaleString()} p/s`;
- }
- let gridLines = '';
- for (let i = 0; i <= 5; i++) {
- const y = 8 + (i * (h - 18) / 5);
- const valAtLevel = Math.round(maxVal * (5 - i) / 5);
- const label = unit === 'bps' ? formatBps(valAtLevel) : `${valAtLevel} p/s`;
- gridLines += `
- <line x1="0" y1="${y.toFixed(1)}" x2="${graphWidth}" y2="${y.toFixed(1)}" stroke="#1e2c3e" stroke-width="1" />
- <text x="${w - 2}" y="${(y + 3).toFixed(1)}" fill="#64748b" font-size="9" font-family="monospace" text-anchor="end">${label}</text>
- `;
- }
- const step = graphWidth / (dataArray.length - 1);
- const points = dataArray.map((val, idx) => {
- const x = idx * step;
- const y = (h - 10) - (val / maxVal) * (h - 20);
- return `${x.toFixed(1)},${y.toFixed(1)}`;
- });
- const polylineStr = points.join(' ');
- const areaPath = `M 0,${h - 10} L ${polylineStr} L ${graphWidth},${h - 10} Z`;
- svg.innerHTML = `
- ${gridLines}
- <path d="${areaPath}" fill="rgba(14, 165, 233, 0.12)" />
- <polyline fill="none" stroke="#38bdf8" stroke-width="1.8" stroke-linejoin="round" points="${polylineStr}" />
- <circle cx="${graphWidth}" cy="${points[points.length - 1].split(',')[1]}" r="3" fill="#38bdf8" />
- `;
- }
- async function moveFilterRule(id, dir) {
- id = decodeURIComponent(id);
- try {
- const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ direction: dir })
- });
- if (!res.ok) throw new Error(await responseError(res));
- await loadFirewall(false);
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function toggleFilterRuleState(id, disabled) {
- id = decodeURIComponent(id);
- try {
- const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ disabled })
- });
- if (!res.ok) throw new Error(await responseError(res));
- await loadFirewall(false);
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deleteFilterRule(id) {
- id = decodeURIComponent(id);
- if (!confirm('Are you sure you want to delete this filter rule?')) return;
- try {
- const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
- if (!res.ok) throw new Error(await responseError(res));
- {
- showToast('Deleted', 'Filter rule removed', 'success');
- loadFirewall(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // ----------------- NAT Rules -----------------
- function renderNATRules() {
- const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
- const tbody = document.getElementById('nat-table-body');
- const empty = document.getElementById('nat-empty');
- if (!tbody) return;
- tbody.innerHTML = '';
- const rules = (state.natRules || []).filter(r => !chainFilter || nativeNATChain(r.chain) === chainFilter);
- document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
- if (rules.length === 0) {
- empty?.classList.remove('hidden');
- return;
- }
- empty?.classList.add('hidden');
- rules.forEach((raw, idx) => {
- const r = safeFirewallRow(raw);
- const tr = document.createElement('tr');
- tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
-
- let toTarget = '-';
- if (r.action === 'jump') {
- toTarget = `<span class="text-yellow-300 font-mono font-bold">→ ${r.jump_target || '-'}</span>`;
- } else if (r.action.includes('address-list') || r.action.includes('address list')) {
- toTarget = `<span class="text-emerald-300 font-mono font-bold">→ ${r.address_list || '-'}</span>`;
- } else if (r.action === 'redirect') {
- toTarget = `<span class="text-amber-300 font-mono font-bold">ports:${r.to_ports || 'all'}</span>`;
- } else if (r.action === 'masquerade') {
- 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>`;
- } else if (r.action === 'log') {
- toTarget = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
- } else {
- const parts = [r.to_addresses, r.to_ports].filter(Boolean);
- toTarget = parts.length ? `<span class="text-amber-300 font-mono font-bold">${parts.join(':')}</span>` : '-';
- }
- const ifaces = [r.out_interface ? 'out:' + r.out_interface : r.out_interface_list ? 'out-list:' + r.out_interface_list : '', r.in_interface ? 'in:' + r.in_interface : r.in_interface_list ? 'in-list:' + r.in_interface_list : ''].filter(Boolean).join(' ');
- tr.innerHTML = `
- <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
- <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
- <td class="py-2.5 px-3 font-bold text-amber-400">${escapeHtml(nativeNATChain(raw.chain).toUpperCase())}</td>
- <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
- <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
- <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}${r.dst_port ? ':' + r.dst_port : ''} <span class="text-[9px] text-slate-500">IPv${r.ip_version || 4}</span></td>
- <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
- <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
- <td class="py-2.5 px-3 font-mono text-xs">${toTarget}</td>
- <td class="py-2.5 px-3 text-[11px] text-slate-400">
- <span class="text-slate-300" id="nat-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
- <span class="text-slate-500" id="nat-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
- </td>
- <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
- <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
- <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
- <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
- <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>
- <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
- <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
- </td>
- `;
- tbody.appendChild(tr);
- });
- }
- // ==================== FIREWALL NAT MODAL (DEBTIK WEBFIG / WINBOX V4) ====================
- function switchNATRuleTab(tab) {
- if (!document.getElementById(`nat-pane-${tab}`)) tab = 'general';
- state.activeNATRuleTab = tab;
- document.querySelectorAll('.nat-rule-tab-btn').forEach(btn => {
- btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
- btn.classList.add('text-slate-400', 'border-transparent');
- });
- const activeBtn = document.getElementById(`nat-tab-btn-${tab}`);
- if (activeBtn) {
- activeBtn.classList.remove('text-slate-400', 'border-transparent');
- activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
- }
- document.querySelectorAll('.nat-rule-pane').forEach(p => p.classList.add('hidden'));
- const activePane = document.getElementById(`nat-pane-${tab}`);
- if (activePane) activePane.classList.remove('hidden');
- if (tab === 'statistics') {
- startNATStatPolling();
- } else {
- stopNATStatPolling();
- }
- }
- function toggleNATField(fieldKey, expand) {
- const plusBtn = document.getElementById(`nat-plus-${fieldKey}`);
- const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
- if (!plusBtn || !fieldBox) return;
- if (expand) {
- plusBtn.classList.add('hidden');
- fieldBox.classList.remove('hidden');
- const valInput = document.getElementById(`nat-val-${fieldKey}`);
- if (valInput) valInput.focus();
- } else {
- fieldBox.classList.add('hidden');
- plusBtn.classList.remove('hidden');
- const valInput = document.getElementById(`nat-val-${fieldKey}`);
- if (valInput) {
- if (valInput.tagName === 'SELECT') {
- valInput.selectedIndex = 0;
- } else {
- valInput.value = '';
- }
- }
- const invInput = document.getElementById(`nat-inv-${fieldKey}`);
- if (invInput) invInput.checked = false;
- if (fieldKey === 'days') {
- ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
- const el = document.getElementById(`nat-day-${d}`);
- if (el) el.checked = true;
- });
- }
- }
- }
- function setNATFieldVal(fieldKey, value, hasInvert = false) {
- if (fieldKey === 'ipsec' && typeof value === 'string') value = value.replace(':', ',');
- if (value !== undefined && value !== null && value !== '' && !(fieldKey === 'proto' && value === 'all')) {
- toggleNATField(fieldKey, true);
- let strVal = String(value);
- if (hasInvert) {
- const inv = strVal.startsWith('!');
- if (inv) strVal = strVal.slice(1);
- const invEl = document.getElementById(`nat-inv-${fieldKey}`);
- if (invEl) invEl.checked = inv;
- else if (inv) strVal = '!'+strVal;
- }
- const valEl = document.getElementById(`nat-val-${fieldKey}`);
- if (valEl) { if (valEl.tagName === 'SELECT' && !Array.from(valEl.options).some(o => o.value === strVal)) { const option=document.createElement('option'); option.value=strVal; option.textContent=strVal+' (saved)'; valEl.appendChild(option); } valEl.value = strVal; }
- } else {
- toggleNATField(fieldKey, false);
- }
- }
- function getNATFieldVal(fieldKey, hasInvert = false) {
- const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
- if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
- const valEl = document.getElementById(`nat-val-${fieldKey}`);
- let v = valEl ? valEl.value.trim() : '';
- if (!v) return '';
- if (hasInvert) {
- const invEl = document.getElementById(`nat-inv-${fieldKey}`);
- if (invEl && invEl.checked) {
- v = '!' + v.replace(/^!/, '');
- }
- }
- return v;
- }
- function toggleMaximizeNATModal() {
- const win = document.getElementById('nat-modal-window');
- if (!win) return;
- if (win.classList.contains('max-w-[720px]')) {
- win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
- win.classList.add('max-w-[96vw]', 'h-[94vh]');
- } else {
- win.classList.remove('max-w-[96vw]', 'h-[94vh]');
- win.classList.add('max-w-[720px]', 'max-h-[92vh]');
- }
- }
- function syncNATChainFromSelect() {
- const sel = document.getElementById('nat-modal-chain-select');
- const customWrap = document.getElementById('nat-modal-custom-wrap');
- const customInput = document.getElementById('nat-modal-custom-input');
- const chainInput = document.getElementById('nat-modal-chain');
- if (!sel || !chainInput) return;
- if (sel.value === '__custom__') {
- if (customWrap) customWrap.classList.remove('hidden');
- if (customInput) {
- customInput.value = '';
- customInput.focus();
- }
- chainInput.value = '';
- } else {
- if (customWrap) customWrap.classList.add('hidden');
- chainInput.value = sel.value;
- const actEl = document.getElementById('nat-modal-action');
- if (actEl) {
- const curAct = actEl.value;
- if (sel.value === 'prerouting' && ['masquerade', 'src-nat'].includes(curAct)) {
- actEl.value = 'dst-nat';
- } else if (sel.value === 'postrouting' && ['dst-nat', 'redirect'].includes(curAct)) {
- actEl.value = 'masquerade';
- }
- }
- }
- handleNATChainChange();
- }
- function syncNATCustomChainInput() {
- const customInput = document.getElementById('nat-modal-custom-input');
- const chainInput = document.getElementById('nat-modal-chain');
- if (customInput && chainInput) {
- chainInput.value = customInput.value.trim();
- }
- handleNATChainChange();
- }
- function handleNATChainChange() {
- const chainInput = document.getElementById('nat-modal-chain');
- const rawChain = (chainInput?.value || 'postrouting').trim();
- const chain = nativeNATChain(rawChain).toLowerCase();
- const sel = document.getElementById('nat-modal-chain-select');
- if (sel && sel.value !== chain && sel.value !== '__custom__') {
- if (['postrouting', 'prerouting', 'output', 'input'].includes(chain)) {
- sel.value = chain;
- }
- }
- const hintEl = document.getElementById('nat-chain-hint');
- if (hintEl) {
- if (chain === 'prerouting') {
- hintEl.textContent = 'PREROUTING: destination NAT (DNAT / REDIRECT) before routing decision (In-Interface only).';
- } else if (chain === 'postrouting') {
- hintEl.textContent = 'POSTROUTING: source NAT (SNAT / MASQUERADE) after routing decision (Out-Interface only).';
- } else if (chain === 'output') {
- hintEl.textContent = 'OUTPUT: destination NAT for locally generated packets (Out-Interface only).';
- } else if (chain === 'input') {
- hintEl.textContent = 'INPUT: source NAT for packets destined to local sockets (In-Interface only).';
- } else {
- hintEl.textContent = `Custom chain "${rawChain}": user-defined NAT chain reached via JUMP.`;
- }
- }
- const rowIn = document.getElementById('nat-row-iniface');
- const rowInList = document.getElementById('nat-row-inifacelist');
- const rowOut = document.getElementById('nat-row-outiface');
- const rowOutList = document.getElementById('nat-row-outifacelist');
- const rowInBridge = document.getElementById('nat-row-inbridgeport');
- const rowOutBridge = document.getElementById('nat-row-outbridgeport');
- const rowSrcMac = document.getElementById('nat-row-srcmac');
- if (chain === 'prerouting' || chain === 'input') {
- if (rowIn) rowIn.classList.remove('hidden');
- if (rowInList) rowInList.classList.remove('hidden');
- if (rowOut) rowOut.classList.add('hidden');
- if (rowOutList) rowOutList.classList.add('hidden');
- if (rowInBridge) rowInBridge.classList.remove('hidden');
- if (rowOutBridge) rowOutBridge.classList.add('hidden');
- if (rowSrcMac) rowSrcMac.classList.remove('hidden');
- } else if (chain === 'postrouting' || chain === 'output') {
- if (rowIn) rowIn.classList.add('hidden');
- if (rowInList) rowInList.classList.add('hidden');
- if (rowOut) rowOut.classList.remove('hidden');
- if (rowOutList) rowOutList.classList.remove('hidden');
- if (rowInBridge) rowInBridge.classList.add('hidden');
- if (rowOutBridge) rowOutBridge.classList.remove('hidden');
- if (rowSrcMac) rowSrcMac.classList.add('hidden');
- } else {
- if (rowIn) rowIn.classList.remove('hidden');
- if (rowInList) rowInList.classList.remove('hidden');
- if (rowOut) rowOut.classList.remove('hidden');
- if (rowOutList) rowOutList.classList.remove('hidden');
- if (rowInBridge) rowInBridge.classList.remove('hidden');
- if (rowOutBridge) rowOutBridge.classList.remove('hidden');
- if (rowSrcMac) rowSrcMac.classList.remove('hidden');
- }
- checkNATActionChainCompatibility();
- toggleNATActionFields();
- }
- function checkNATActionChainCompatibility() {
- const rawChain = (document.getElementById('nat-modal-chain')?.value || 'postrouting').trim();
- const chain = nativeNATChain(rawChain).toLowerCase();
- const action = (document.getElementById('nat-modal-action')?.value || '').toLowerCase();
- const warnBox = document.getElementById('nat-action-incompatible-warn');
- const warnMsg = document.getElementById('nat-action-incompatible-msg');
- if (!warnBox || !warnMsg) return;
- let msg = '';
- if (['dst-nat', 'redirect'].includes(action)) {
- if (chain !== 'prerouting' && chain !== 'output') {
- msg = `${action === 'dst-nat' ? 'DNAT' : 'REDIRECT'} is only valid in PREROUTING or OUTPUT chains in iptables (current chain: ${chain.toUpperCase()}).`;
- }
- } else if (action === 'masquerade') {
- if (chain !== 'postrouting') {
- msg = `MASQUERADE is only valid in the POSTROUTING chain in iptables (current chain: ${chain.toUpperCase()}).`;
- }
- } else if (action === 'src-nat') {
- if (chain !== 'postrouting' && chain !== 'input') {
- msg = `SNAT is only valid in POSTROUTING or INPUT chains in iptables (current chain: ${chain.toUpperCase()}).`;
- }
- }
- if (msg) {
- warnMsg.textContent = msg;
- warnBox.classList.remove('hidden');
- } else {
- warnBox.classList.add('hidden');
- }
- }
- function toggleNATActionFields() {
- const act = document.getElementById('nat-modal-action')?.value || 'masquerade';
- const rowAddr = document.getElementById('nat-row-toaddr');
- const rowPort = document.getElementById('nat-row-toport');
- const jumpBox = document.getElementById('nat-action-jump-box');
- const addrBox = document.getElementById('nat-action-addrlist-box');
- // Hide all dynamic rows first
- if (rowAddr) rowAddr.classList.add('hidden');
- if (rowPort) rowPort.classList.add('hidden');
- if (jumpBox) jumpBox.classList.add('hidden');
- if (addrBox) addrBox.classList.add('hidden');
- if (['src-nat', 'dst-nat', 'netmap'].includes(act)) {
- if (rowAddr) rowAddr.classList.remove('hidden');
- if (rowPort && act !== 'netmap') rowPort.classList.remove('hidden');
- } else if (act === 'redirect' || act === 'masquerade') {
- if (rowPort) rowPort.classList.remove('hidden');
- } else if (act === 'jump') {
- if (jumpBox) jumpBox.classList.remove('hidden');
- } else if (act.includes('address-list') || act.includes('address list')) {
- if (addrBox) addrBox.classList.remove('hidden');
- }
- if (act === 'log') {
- const logEl = document.getElementById('nat-modal-log');
- if (logEl) logEl.checked = true;
- toggleNATField('logprefix', true);
- }
- }
- function handleNATActionChange() {
- toggleNATActionFields();
- checkNATActionChainCompatibility();
- }
- function toggleNATLogPrefix() {
- const isLog = document.getElementById('nat-modal-log')?.checked;
- toggleNATField('logprefix', !!isLog);
- }
- function openAddNATModal() {
- const tos = document.getElementById('nat-val-tos'); if (tos) tos.value = '';
- switchNATRuleTab('general');
- setFirewallDays('nat', '');
- const badge = document.getElementById('nat-modal-badge');
- if (badge) badge.innerText = 'New...';
- document.getElementById('nat-modal-id').value = '';
- document.getElementById('nat-modal-family').value = '4';
- document.getElementById('nat-modal-enabled').checked = true;
- document.getElementById('nat-modal-comment').value = '';
- document.getElementById('nat-modal-chain').value = 'postrouting';
- populateChainDropdown('nat', 'postrouting');
- handleNATChainChange();
- document.getElementById('nat-modal-action').value = 'masquerade';
- document.getElementById('nat-modal-toaddr').value = '';
- document.getElementById('nat-modal-toport').value = '';
- document.getElementById('nat-modal-log').checked = false;
- populateInterfaceSelect('nat-val-iniface');
- populateInterfaceSelect('nat-val-outiface');
- populateAddressListSelect('nat-val-srclist');
- populateAddressListSelect('nat-val-dstlist');
- populateGeoIPSelect('nat-val-srcgeo');
- populateGeoIPSelect('nat-val-dstgeo');
- const allFieldKeys = [
- 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
- 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
- 'routingmark', 'conntype',
- 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
- 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
- 'ipsec', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
- 'pktsize', 'random', 'icmpoptions', 'ipv4options', 'ttl',
- 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
- ];
- allFieldKeys.forEach(k => toggleNATField(k, false));
- resetNATCounterDisplay();
- toggleNATActionFields();
- document.getElementById('nat-modal').classList.remove('hidden');
- }
- function openEditNATModal(id) {
- id = decodeURIComponent(id);
- const r = (state.natRules || []).find(rule => rule.id === id);
- if (!r) return;
- setFirewallDays('nat', r.days || '');
- switchNATRuleTab('general');
- const badge = document.getElementById('nat-modal-badge');
- if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
- document.getElementById('nat-modal-id').value = r.id;
- document.getElementById('nat-modal-family').value = String(r.ip_version || 4);
- document.getElementById('nat-modal-enabled').checked = !r.disabled;
- document.getElementById('nat-modal-comment').value = r.comment || '';
- const natChain = nativeNATChain(r.chain || 'postrouting');
- document.getElementById('nat-modal-chain').value = natChain;
- populateChainDropdown('nat', natChain);
- handleNATChainChange();
- setFirewallActionSelection('nat', r.action || 'accept');
- document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
- document.getElementById('nat-modal-toport').value = r.to_ports || '';
- document.getElementById('nat-modal-log').checked = !!r.log;
- populateInterfaceSelect('nat-val-iniface', (r.in_interface || '').replace(/^!/, ''));
- populateInterfaceSelect('nat-val-outiface', (r.out_interface || '').replace(/^!/, ''));
- populateAddressListSelect('nat-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
- populateAddressListSelect('nat-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
- populateGeoIPSelect('nat-val-srcgeo', r.src_geoip || '');
- populateGeoIPSelect('nat-val-dstgeo', r.dst_geoip || '');
- setNATFieldVal('src', r.src_address, true);
- setNATFieldVal('dst', r.dst_address, true);
- setNATFieldVal('srclist', r.src_address_list, true);
- setNATFieldVal('dstlist', r.dst_address_list, true);
- setNATFieldVal('srcgeo', r.src_geoip, true);
- setNATFieldVal('dstgeo', r.dst_geoip, true);
- if (r.protocol && r.protocol !== 'all') {
- setNATFieldVal('proto', r.protocol, true);
- } else {
- toggleNATField('proto', false);
- }
- setNATFieldVal('sport', r.src_port, true);
- setNATFieldVal('dport', r.dst_port, true);
- setNATFieldVal('anyport', r.any_port, true);
- setNATFieldVal('iniface', r.in_interface, true);
- setNATFieldVal('outiface', r.out_interface, true);
- setNATFieldVal('inifacelist', r.in_interface_list, true);
- setNATFieldVal('outifacelist', r.out_interface_list, true);
- setNATFieldVal('pktmark', r.packet_mark, true);
- setNATFieldVal('connmark', r.connection_mark, true);
- setNATFieldVal('routingmark', r.routing_mark, true);
- setNATFieldVal('conntype', r.connection_type, false);
- // Advanced tab fields
- setNATFieldVal('layer7', r.layer7_protocol, false);
- setNATFieldVal('content', r.content, false);
- setNATFieldVal('connbytes', r.connection_bytes, false);
- setNATFieldVal('connrate', r.connection_rate, false);
- setNATFieldVal('pcc', r.pcc, false);
- setNATFieldVal('srcmac', r.src_mac_address, true);
- setNATFieldVal('outbridgeport', r.out_bridge_port, false);
- setNATFieldVal('inbridgeport', r.in_bridge_port, false);
- setNATFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
- setNATFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
- setNATFieldVal('ipsec', r.ipsec_policy, false);
- setNATFieldVal('ingresspriority', r.ingress_priority, false);
- setNATFieldVal('priority', r.priority, false);
- setNATFieldVal('dscp', r.dscp, false);
- setNATFieldVal('tcpmss', r.tcp_mss, false);
- { const tosEl = document.getElementById('nat-val-tos'); if (tosEl) tosEl.value = r.tos || ''; }
- setNATFieldVal('pktsize', r.packet_size, false);
- setNATFieldVal('random', r.random, false);
- setNATFieldVal('icmpoptions', r.icmp_options, false);
- setNATFieldVal('ipv4options', r.ipv4_options, false);
- setNATFieldVal('ttl', r.ttl, false);
- // Extra tab fields
- setNATFieldVal('time', r.time, false);
- if (r.days) {
- toggleNATField('days', true);
- ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
- const chk = document.getElementById(`nat-day-${d}`);
- if (chk) chk.checked = r.days.toLowerCase().includes(d);
- });
- } else {
- toggleNATField('days', false);
- }
- setNATFieldVal('limit', r.limit, false);
- setNATFieldVal('dstlimit', r.dst_limit, false);
- setNATFieldVal('psd', r.psd, false);
- // Action fields
- if (r.jump_target) {
- const jtEl = document.getElementById('nat-modal-jumptarget');
- if (jtEl) jtEl.value = r.jump_target;
- }
- if (r.address_list) {
- const alEl = document.getElementById('nat-modal-action-addrlist');
- if (alEl) alEl.value = r.address_list;
- }
- if (r.address_list_timeout) {
- const toEl = document.getElementById('nat-modal-action-timeout');
- if (toEl) toEl.value = r.address_list_timeout;
- }
- setNATFieldVal('logprefix', r.log_prefix, false);
- // Statistics
- const bEl = document.getElementById('nat-stat-bytes');
- const pEl = document.getElementById('nat-stat-packets');
- if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
- if (pEl) pEl.value = (r.packets || 0).toLocaleString();
- state.natLastBytes = r.bytes || 0;
- state.natLastPackets = r.packets || 0;
- state.natLastTimestamp = Date.now();
- state.natStatRateHistory = new Array(30).fill(0);
- state.natStatPktHistory = new Array(30).fill(0);
- renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
- renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
- toggleNATActionFields();
- document.getElementById('nat-modal').classList.remove('hidden');
- }
- function closeNATModal() {
- stopNATStatPolling();
- document.getElementById('nat-modal').classList.add('hidden');
- }
- function copyNATRule() {
- document.getElementById('nat-modal-id').value = '';
- const badge = document.getElementById('nat-modal-badge');
- if (badge) badge.innerText = 'New...';
- showToast('Rule Cloned', 'Ready to save as a new NAT rule copy', 'info');
- }
- function resetNATCounterDisplay() {
- state.natStatRateHistory = new Array(30).fill(0);
- state.natStatPktHistory = new Array(30).fill(0);
- state.natLastBytes = 0;
- state.natLastPackets = 0;
- state.natLastTimestamp = Date.now();
- const bEl = document.getElementById('nat-stat-bytes');
- const pEl = document.getElementById('nat-stat-packets');
- const rEl = document.getElementById('nat-stat-rate');
- const prEl = document.getElementById('nat-stat-pktrate');
- if (bEl) bEl.value = '0 B';
- if (pEl) pEl.value = '0';
- if (rEl) rEl.value = '0 bps';
- if (prEl) prEl.value = '0 p/s';
- renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
- renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
- showToast('Counters Reset', 'NAT rule counter display reset to 0', 'info');
- }
- async function applyNATRule(closeAfter = false) {
- const id = document.getElementById('nat-modal-id').value;
- if (!reviewLegacyFirewallSettings('nat', id)) return;
- let selectedDays; try { selectedDays = getFirewallDays('nat'); } catch(error) { showToast('Error', error.message, 'error'); return; }
- const chain = (document.getElementById('nat-modal-chain').value || '').trim();
- const chainLower = nativeNATChain(chain).toLowerCase();
- const action = document.getElementById('nat-modal-action').value;
- const comment = document.getElementById('nat-modal-comment').value.trim();
- const enabled = document.getElementById('nat-modal-enabled').checked;
- const src = getNATFieldVal('src', true);
- const dst = getNATFieldVal('dst', true);
- const srclist = getNATFieldVal('srclist', true);
- const dstlist = getNATFieldVal('dstlist', true);
- const srcgeo = getNATFieldVal('srcgeo', true);
- const dstgeo = getNATFieldVal('dstgeo', true);
- const proto = getNATFieldVal('proto', true);
- const sport = getNATFieldVal('sport', true);
- const dport = getNATFieldVal('dport', true);
- const anyport = getNATFieldVal('anyport', true);
- let iniface = getNATFieldVal('iniface', true);
- let outiface = getNATFieldVal('outiface', true);
- let inifacelist = getNATFieldVal('inifacelist', true);
- let outifacelist = getNATFieldVal('outifacelist', true);
- if (chainLower === 'prerouting' || chainLower === 'input') {
- outiface = '';
- outifacelist = '';
- } else if (chainLower === 'postrouting' || chainLower === 'output') {
- iniface = '';
- inifacelist = '';
- }
- const pktmark = getNATFieldVal('pktmark', true);
- const connmark = getNATFieldVal('connmark', true);
- const routingmark = getNATFieldVal('routingmark', true);
- const conntype = getNATFieldVal('conntype', false);
- const usesAddr = ['src-nat', 'dst-nat', 'netmap'].includes(action);
- const usesPort = ['src-nat', 'dst-nat', 'redirect', 'masquerade'].includes(action);
- if (!chain) { switchNATRuleTab('general'); showToast('NAT rule', 'Enter a chain.', 'error'); document.getElementById('nat-modal-chain').focus(); return; }
- if (chainLower === 'forward') { switchNATRuleTab('general'); showToast('Invalid Chain', 'Chain FORWARD is not valid in the NAT table in iptables.', 'error'); return; }
- if (['dst-nat', 'redirect'].includes(action) && chainLower !== 'prerouting' && chainLower !== 'output') {
- switchNATRuleTab('general');
- showToast('Invalid Target for Chain', `${action === 'dst-nat' ? 'DNAT' : 'REDIRECT'} requires PREROUTING or OUTPUT chain in iptables.`, 'error');
- return;
- }
- if (action === 'masquerade' && chainLower !== 'postrouting') {
- switchNATRuleTab('general');
- showToast('Invalid Target for Chain', 'MASQUERADE requires POSTROUTING chain in iptables.', 'error');
- return;
- }
- if (action === 'src-nat' && chainLower !== 'postrouting' && chainLower !== 'input') {
- switchNATRuleTab('general');
- showToast('Invalid Target for Chain', 'SNAT requires POSTROUTING or INPUT chain in iptables.', 'error');
- return;
- }
- if (usesAddr && !document.getElementById('nat-modal-toaddr').value.trim()) { switchNATRuleTab('general'); showToast('NAT rule', 'Enter the destination IP / address for this action.', 'error'); document.getElementById('nat-modal-toaddr').focus(); return; }
- if ((sport || dport || anyport || (usesPort && document.getElementById('nat-modal-toport').value.trim())) && !['tcp', 'udp'].includes(proto)) {
- switchNATRuleTab('general'); toggleNATField('proto', true); document.getElementById('nat-val-proto').value = proto || 'all';
- showToast('Select protocol', 'Port rules require TCP or UDP. For DNS, create one UDP and one TCP rule.', 'error'); document.getElementById('nat-val-proto').focus(); return;
- }
- const payload = {
- ip_version: Number(document.getElementById('nat-modal-family').value),
- id,
- chain,
- action,
- to_addresses: usesAddr ? (document.getElementById('nat-modal-toaddr')?.value.trim() || '') : '',
- to_ports: usesPort ? (document.getElementById('nat-modal-toport')?.value.trim() || '') : '',
- protocol: proto || 'all',
- src_address: src,
- dst_address: dst,
- src_port: sport,
- dst_port: dport,
- any_port: anyport,
- in_interface: iniface,
- out_interface: outiface,
- in_interface_list: inifacelist,
- out_interface_list: outifacelist,
- packet_mark: pktmark,
- connection_mark: connmark,
- routing_mark: routingmark,
- connection_type: conntype,
- src_address_list: srclist,
- dst_address_list: dstlist,
- src_geoip: srcgeo,
- dst_geoip: dstgeo,
- comment,
- disabled: !enabled,
- // Advanced tab
- content: getNATFieldVal('content', false),
- src_mac_address: (chainLower === 'output' || chainLower === 'postrouting') ? '' : getNATFieldVal('srcmac', true),
- out_bridge_port: (chainLower === 'input' || chainLower === 'prerouting') ? '' : getNATFieldVal('outbridgeport', false),
- in_bridge_port: (chainLower === 'output' || chainLower === 'postrouting') ? '' : getNATFieldVal('inbridgeport', false),
- ipsec_policy: getNATFieldVal('ipsec', false),
- dscp: getNATFieldVal('dscp', false),
- tcp_mss: getNATFieldVal('tcpmss', false),
- tos: document.getElementById('nat-val-tos')?.value || '',
- packet_size: getNATFieldVal('pktsize', false),
- random: getNATFieldVal('random', false),
- icmp_options: getNATFieldVal('icmpoptions', false),
- ttl: getNATFieldVal('ttl', false),
- days: selectedDays,
- // Extra tab
- time: getNATFieldVal('time', false),
- limit: getNATFieldVal('limit', false),
- // Action tab
- jump_target: action === 'jump' ? (document.getElementById('nat-modal-jumptarget')?.value || '') : '',
- address_list: action.includes('address') ? (document.getElementById('nat-modal-action-addrlist')?.value || '') : '',
- address_list_timeout: action.includes('address') ? (document.getElementById('nat-modal-action-timeout')?.value || '') : '',
- log: document.getElementById('nat-modal-log')?.checked || false,
- log_prefix: getNATFieldVal('logprefix', false)
- };
- try {
- const res = await fetch(`${API_BASE}/firewall/nat`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(payload)
- });
- if (res.ok) {
- const data = await res.json();
- showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
- loadFirewall(false);
- if (closeAfter) {
- closeNATModal();
- } else {
- if (data.id) {
- document.getElementById('nat-modal-id').value = data.id;
- const badge = document.getElementById('nat-modal-badge');
- if (badge) badge.innerText = `#${data.id}`;
- }
- }
- } else {
- const err = await res.json();
- showToast('Error', err.message || 'Failed to save rule', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- function submitSaveNATRule(e) {
- if (e && e.preventDefault) e.preventDefault();
- return applyNATRule(true);
- }
- function startNATStatPolling() {
- stopNATStatPolling();
- pollNATRuleStats();
- state.natStatInterval = setInterval(pollNATRuleStats, 1000);
- }
- function stopNATStatPolling() {
- if (state.natStatInterval) {
- clearInterval(state.natStatInterval);
- state.natStatInterval = null;
- }
- }
- async function pollNATRuleStats() {
- const id = document.getElementById('nat-modal-id')?.value;
- if (!id) {
- renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory || new Array(30).fill(0), 'bps', 'nat-stat-legend-rate');
- renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory || new Array(30).fill(0), 'p/s', 'nat-stat-legend-pktrate');
- return;
- }
- try {
- const res = await fetch(`${API_BASE}/firewall/nat`);
- if (!res.ok) return;
- const rules = await res.json();
- const r = rules.find(x => x.id === id);
- if (!r) return;
- const now = Date.now();
- const dt = Math.max(0.2, (now - (state.natLastTimestamp || now)) / 1000);
- state.natLastTimestamp = now;
- const curBytes = r.bytes || 0;
- const curPackets = r.packets || 0;
- const deltaBytes = Math.max(0, curBytes - (state.natLastBytes ?? curBytes));
- const deltaPkts = Math.max(0, curPackets - (state.natLastPackets ?? curPackets));
- state.natLastBytes = curBytes;
- state.natLastPackets = curPackets;
- const rateBps = Math.round((deltaBytes * 8) / dt);
- const ratePkt = Math.round(deltaPkts / dt);
- if (!state.natStatRateHistory) state.natStatRateHistory = new Array(30).fill(0);
- if (!state.natStatPktHistory) state.natStatPktHistory = new Array(30).fill(0);
- state.natStatRateHistory.push(rateBps);
- if (state.natStatRateHistory.length > 30) state.natStatRateHistory.shift();
- state.natStatPktHistory.push(ratePkt);
- if (state.natStatPktHistory.length > 30) state.natStatPktHistory.shift();
- const bEl = document.getElementById('nat-stat-bytes');
- const pEl = document.getElementById('nat-stat-packets');
- const rEl = document.getElementById('nat-stat-rate');
- const prEl = document.getElementById('nat-stat-pktrate');
- if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
- if (pEl) pEl.value = curPackets.toLocaleString();
- if (rEl) rEl.value = formatBps(rateBps);
- if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
- renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
- renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
- } catch (e) {
- console.error('Error polling NAT rule stats', e);
- }
- }
- async function moveNATRule(id, dir) {
- id = decodeURIComponent(id);
- try {
- const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ direction: dir })
- });
- if (!res.ok) throw new Error(await responseError(res));
- await loadFirewall(false);
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function toggleNATRuleState(id, disabled) {
- id = decodeURIComponent(id);
- try {
- const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ disabled })
- });
- if (!res.ok) throw new Error(await responseError(res));
- await loadFirewall(false);
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deleteNATRule(id) {
- id = decodeURIComponent(id);
- if (!confirm('Are you sure you want to delete this NAT rule?')) return;
- try {
- const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
- if (!res.ok) throw new Error(await responseError(res));
- {
- showToast('Deleted', 'NAT rule removed', 'success');
- loadFirewall(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // ----------------- Mangle Rules -----------------
- function renderMangleRules() {
- const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
- const tbody = document.getElementById('mangle-table-body');
- const empty = document.getElementById('mangle-empty');
- if (!tbody) return;
- tbody.innerHTML = '';
- const rules = (state.mangleRules || []).filter(r => !chainFilter || (r.chain || '').toLowerCase() === chainFilter);
- document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
- if (rules.length === 0) {
- empty?.classList.remove('hidden');
- return;
- }
- empty?.classList.add('hidden');
- rules.forEach((raw, idx) => {
- const r = safeFirewallRow(raw);
- const tr = document.createElement('tr');
- tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
- let markVal = '<span class="text-slate-500">-</span>';
- if (r.new_connection_mark) markVal = `<span class="text-cyan-300 font-mono font-bold">${r.new_connection_mark}</span>`;
- else if (r.new_routing_mark) markVal = `<span class="text-amber-300 font-mono font-bold">${r.new_routing_mark}</span>`;
- else if (r.new_packet_mark) markVal = `<span class="text-emerald-300 font-mono font-bold">${r.new_packet_mark}</span>`;
- else if (r.new_mss) markVal = `<span class="text-sky-300 font-mono font-bold">mss:${r.new_mss}</span>`;
- else if (r.action === 'change-dscp') markVal = `<span class="text-purple-300 font-mono font-bold">dscp:${r.new_dscp}</span>`;
- else if (r.new_ttl) markVal = `<span class="text-blue-300 font-mono font-bold">ttl:${r.new_ttl}</span>`;
- else if (r.new_priority) markVal = `<span class="text-indigo-300 font-mono font-bold">prio:${r.new_priority}</span>`;
- else if (r.route) markVal = `<span class="text-orange-300 font-mono font-bold">route:${r.route}</span>`;
- else if (r.sniff_target) markVal = `<span class="text-pink-300 font-mono font-bold">sniff:${r.sniff_target}</span>`;
- else if (r.action === 'jump') markVal = `<span class="text-yellow-300 font-mono font-bold">→ ${r.jump_target || '-'}</span>`;
- else if (r.action.includes('address-list') || r.action.includes('address list')) markVal = `<span class="text-emerald-300 font-mono font-bold">→ ${r.address_list || '-'}</span>`;
- else if (r.action === 'log') markVal = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
- tr.innerHTML = `
- <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
- <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
- <td class="py-2.5 px-3 font-bold text-purple-400">${(r.chain || '').toUpperCase()}</td>
- <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
- <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
- <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
- <td class="py-2.5 px-3 font-mono text-xs">${markVal}</td>
- <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>
- <td class="py-2.5 px-3 text-[11px] text-slate-400">
- <span class="text-slate-300" id="mangle-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
- <span class="text-slate-500" id="mangle-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
- </td>
- <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
- <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
- <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
- <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
- <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>
- <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
- <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
- </td>
- `;
- tbody.appendChild(tr);
- });
- }
- // ==================== FIREWALL MANGLE MODAL (DEBTIK WEBFIG / WINBOX V4) ====================
- function switchMangleRuleTab(tab) {
- state.activeMangleRuleTab = tab;
- document.querySelectorAll('.mangle-rule-tab-btn').forEach(btn => {
- btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
- btn.classList.add('text-slate-400', 'border-transparent');
- });
- const activeBtn = document.getElementById(`mangle-tab-btn-${tab}`);
- if (activeBtn) {
- activeBtn.classList.remove('text-slate-400', 'border-transparent');
- activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
- }
- document.querySelectorAll('.mangle-rule-pane').forEach(p => p.classList.add('hidden'));
- const activePane = document.getElementById(`mangle-pane-${tab}`);
- if (activePane) activePane.classList.remove('hidden');
- if (tab === 'statistics') {
- startMangleStatPolling();
- } else {
- stopMangleStatPolling();
- }
- }
- function toggleMangleField(fieldKey, expand) {
- const plusBtn = document.getElementById(`mangle-plus-${fieldKey}`);
- const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
- if (!plusBtn || !fieldBox) return;
- if (expand) {
- plusBtn.classList.add('hidden');
- fieldBox.classList.remove('hidden');
- const valInput = document.getElementById(`mangle-val-${fieldKey}`);
- if (valInput) valInput.focus();
- } else {
- fieldBox.classList.add('hidden');
- plusBtn.classList.remove('hidden');
- const valInput = document.getElementById(`mangle-val-${fieldKey}`);
- if (valInput) {
- if (valInput.tagName === 'SELECT') {
- valInput.selectedIndex = 0;
- } else {
- valInput.value = '';
- }
- }
- const invInput = document.getElementById(`mangle-inv-${fieldKey}`);
- if (invInput) invInput.checked = false;
- if (fieldKey === 'cs') {
- ['mangle-modal-cs-established', 'mangle-modal-cs-related', 'mangle-modal-cs-new', 'mangle-modal-cs-invalid', 'mangle-modal-cs-untracked'].forEach(id => {
- const el = document.getElementById(id);
- if (el) el.checked = false;
- });
- }
- if (fieldKey === 'natstate') {
- ['mangle-modal-nat-srcnat', 'mangle-modal-nat-dstnat'].forEach(id => {
- const el = document.getElementById(id);
- if (el) el.checked = false;
- });
- }
- }
- }
- function setMangleFieldVal(fieldKey, value, hasInvert = false) {
- if (fieldKey === 'ipsec' && typeof value === 'string') value = value.replace(':', ',');
- if (value !== undefined && value !== null && value !== '' && !(fieldKey === 'proto' && value === 'all')) {
- toggleMangleField(fieldKey, true);
- let strVal = String(value);
- if (hasInvert) {
- const inv = strVal.startsWith('!');
- if (inv) strVal = strVal.slice(1);
- const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
- if (invEl) invEl.checked = inv;
- else if (inv) strVal = '!'+strVal;
- }
- const valEl = document.getElementById(`mangle-val-${fieldKey}`);
- if (valEl) { if (valEl.tagName === 'SELECT' && !Array.from(valEl.options).some(o => o.value === strVal)) { const option=document.createElement('option'); option.value=strVal; option.textContent=strVal+' (saved)'; valEl.appendChild(option); } valEl.value = strVal; }
- } else {
- toggleMangleField(fieldKey, false);
- }
- }
- function getMangleFieldVal(fieldKey, hasInvert = false) {
- const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
- if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
- const valEl = document.getElementById(`mangle-val-${fieldKey}`);
- let v = valEl ? valEl.value.trim() : '';
- if (!v) return '';
- if (hasInvert) {
- const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
- if (invEl && invEl.checked) {
- v = '!' + v.replace(/^!/, '');
- }
- }
- return v;
- }
- function toggleMaximizeMangleModal() {
- const win = document.getElementById('mangle-modal-window');
- if (!win) return;
- if (win.classList.contains('max-w-[720px]')) {
- win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
- win.classList.add('max-w-[96vw]', 'h-[94vh]');
- } else {
- win.classList.remove('max-w-[96vw]', 'h-[94vh]');
- win.classList.add('max-w-[720px]', 'max-h-[92vh]');
- }
- }
- function syncMangleChainFromSelect() {
- const sel = document.getElementById('mangle-modal-chain-select');
- const customWrap = document.getElementById('mangle-modal-custom-wrap');
- const customInput = document.getElementById('mangle-modal-custom-input');
- const chainInput = document.getElementById('mangle-modal-chain');
- if (!sel || !chainInput) return;
- if (sel.value === '__custom__') {
- if (customWrap) customWrap.classList.remove('hidden');
- if (customInput) {
- customInput.value = '';
- customInput.focus();
- }
- chainInput.value = '';
- } else {
- if (customWrap) customWrap.classList.add('hidden');
- chainInput.value = sel.value;
- }
- handleMangleChainChange();
- }
- function syncMangleCustomChainInput() {
- const customInput = document.getElementById('mangle-modal-custom-input');
- const chainInput = document.getElementById('mangle-modal-chain');
- if (customInput && chainInput) {
- chainInput.value = customInput.value.trim();
- }
- handleMangleChainChange();
- }
- function handleMangleChainChange() {
- const chainInput = document.getElementById('mangle-modal-chain');
- const rawChain = (chainInput?.value || 'prerouting').trim();
- const chain = rawChain.toLowerCase();
- const sel = document.getElementById('mangle-modal-chain-select');
- if (sel && sel.value !== chain && sel.value !== '__custom__') {
- if (['prerouting', 'input', 'forward', 'output', 'postrouting'].includes(chain)) {
- sel.value = chain;
- }
- }
- const hintEl = document.getElementById('mangle-chain-hint');
- if (hintEl) {
- if (chain === 'prerouting') {
- hintEl.textContent = 'PREROUTING: packets altered before routing decision (In-Interface only).';
- } else if (chain === 'input') {
- hintEl.textContent = 'INPUT: packets altered before local socket delivery (In-Interface only).';
- } else if (chain === 'forward') {
- hintEl.textContent = 'FORWARD: transit packets routed through this router (accepts both In and Out interfaces).';
- } else if (chain === 'output') {
- hintEl.textContent = 'OUTPUT: locally generated packets before routing decision (Out-Interface only).';
- } else if (chain === 'postrouting') {
- hintEl.textContent = 'POSTROUTING: packets altered after routing decision before transmission (Out-Interface only; CLASSIFY supported).';
- } else {
- hintEl.textContent = `Custom chain "${rawChain}": user-defined Mangle chain reached via JUMP.`;
- }
- }
- const rowIn = document.getElementById('mangle-row-iniface');
- const rowInList = document.getElementById('mangle-row-inifacelist');
- const rowOut = document.getElementById('mangle-row-outiface');
- const rowOutList = document.getElementById('mangle-row-outifacelist');
- const rowInBridge = document.getElementById('mangle-row-inbridgeport');
- const rowOutBridge = document.getElementById('mangle-row-outbridgeport');
- const rowSrcMac = document.getElementById('mangle-row-srcmac');
- if (chain === 'prerouting' || chain === 'input') {
- if (rowIn) rowIn.classList.remove('hidden');
- if (rowInList) rowInList.classList.remove('hidden');
- if (rowOut) rowOut.classList.add('hidden');
- if (rowOutList) rowOutList.classList.add('hidden');
- if (rowInBridge) rowInBridge.classList.remove('hidden');
- if (rowOutBridge) rowOutBridge.classList.add('hidden');
- if (rowSrcMac) rowSrcMac.classList.remove('hidden');
- } else if (chain === 'output' || chain === 'postrouting') {
- if (rowIn) rowIn.classList.add('hidden');
- if (rowInList) rowInList.classList.add('hidden');
- if (rowOut) rowOut.classList.remove('hidden');
- if (rowOutList) rowOutList.classList.remove('hidden');
- if (rowInBridge) rowInBridge.classList.add('hidden');
- if (rowOutBridge) rowOutBridge.classList.remove('hidden');
- if (rowSrcMac) rowSrcMac.classList.add('hidden');
- } else {
- if (rowIn) rowIn.classList.remove('hidden');
- if (rowInList) rowInList.classList.remove('hidden');
- if (rowOut) rowOut.classList.remove('hidden');
- if (rowOutList) rowOutList.classList.remove('hidden');
- if (rowInBridge) rowInBridge.classList.remove('hidden');
- if (rowOutBridge) rowOutBridge.classList.remove('hidden');
- if (rowSrcMac) rowSrcMac.classList.remove('hidden');
- }
- checkMangleActionChainCompatibility();
- toggleMangleActionFields();
- }
- function checkMangleActionChainCompatibility() {
- const rawChain = (document.getElementById('mangle-modal-chain')?.value || 'prerouting').trim();
- const chain = rawChain.toLowerCase();
- const action = (document.getElementById('mangle-modal-action')?.value || '').toLowerCase();
- const warnBox = document.getElementById('mangle-action-incompatible-warn');
- const warnMsg = document.getElementById('mangle-action-incompatible-msg');
- if (!warnBox || !warnMsg) return;
- let msg = '';
- if (action === 'set-priority' && chain !== 'postrouting') {
- msg = 'CLASSIFY (set-priority) requires the POSTROUTING chain in iptables.';
- }
- if (msg) {
- warnMsg.textContent = msg;
- warnBox.classList.remove('hidden');
- } else {
- warnBox.classList.add('hidden');
- }
- }
- function toggleMangleActionFields() {
- const act = document.getElementById('mangle-modal-action')?.value || 'mark-connection';
-
- // Hide all dynamic rows first
- ['newconnmark', 'newroutingmark', 'newpktmark', 'newmss', 'newdscp', 'newttl', 'newpriority', 'route', 'sniff', 'passthrough'].forEach(id => {
- const el = document.getElementById(`mangle-row-${id}`);
- if (el) el.classList.add('hidden');
- });
- const jumpBox = document.getElementById('mangle-action-jump-box');
- const addrBox = document.getElementById('mangle-action-addrlist-box');
- if (jumpBox) jumpBox.classList.add('hidden');
- if (addrBox) addrBox.classList.add('hidden');
- // Activate matching rows
- if (act === 'mark-connection') {
- document.getElementById('mangle-row-newconnmark')?.classList.remove('hidden');
- document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
- } else if (act === 'mark-routing') {
- document.getElementById('mangle-row-newroutingmark')?.classList.remove('hidden');
- document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
- } else if (act === 'mark-packet') {
- document.getElementById('mangle-row-newpktmark')?.classList.remove('hidden');
- document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
- } else if (act === 'change-mss') {
- document.getElementById('mangle-row-newmss')?.classList.remove('hidden');
- document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
- } else if (act === 'change-dscp') {
- document.getElementById('mangle-row-newdscp')?.classList.remove('hidden');
- document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
- } else if (act === 'change-ttl') {
- document.getElementById('mangle-row-newttl')?.classList.remove('hidden');
- document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
- } else if (act === 'set-priority') {
- document.getElementById('mangle-row-newpriority')?.classList.remove('hidden');
- document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
- } else if (act === 'route') {
- document.getElementById('mangle-row-route')?.classList.remove('hidden');
- document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
- } else if (act === 'sniff-pc' || act === 'sniff-tzsp') {
- document.getElementById('mangle-row-sniff')?.classList.remove('hidden');
- document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
- } else if (act === 'clear-df' || act === 'strip-ipv4-options') {
- document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
- } else if (act === 'jump') {
- if (jumpBox) jumpBox.classList.remove('hidden');
- } else if (act.includes('address-list') || act.includes('address list')) {
- if (addrBox) addrBox.classList.remove('hidden');
- }
- if (act === 'log') {
- const logEl = document.getElementById('mangle-modal-log');
- if (logEl) logEl.checked = true;
- toggleMangleField('logprefix', true);
- }
- checkMangleActionChainCompatibility();
- }
- function toggleMangleLogPrefix() {
- const isLog = document.getElementById('mangle-modal-log')?.checked;
- toggleMangleField('logprefix', !!isLog);
- }
- const allMangleFieldKeys = [
- 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
- 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
- 'routingmark', 'conntype', 'cs', 'natstate',
- 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
- 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
- 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
- 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
- 'nth', 'connlimit', 'srcaddrtype', 'dstaddrtype', 'hotspot', 'ipfragment',
- 'limit', 'dstlimit', 'time', 'psd', 'logprefix'
- ];
- function openAddMangleModal() {
- const tos = document.getElementById('mangle-val-tos'); if (tos) tos.value = '';
- switchMangleRuleTab('general');
- const badge = document.getElementById('mangle-modal-badge');
- if (badge) badge.innerText = 'New...';
- document.getElementById('mangle-modal-id').value = '';
- document.getElementById('mangle-modal-family').value = '4';
- document.getElementById('mangle-modal-enabled').checked = true;
- document.getElementById('mangle-modal-comment').value = '';
- document.getElementById('mangle-modal-chain').value = 'prerouting';
- populateChainDropdown('mangle', 'prerouting');
- handleMangleChainChange();
- document.getElementById('mangle-modal-action').value = 'mark-connection';
-
- if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = '';
- if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = '';
- if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = '';
- if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = '';
- if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = '';
- if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = '';
- if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = '';
- if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = '';
- if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = '';
- if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = '';
- if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = '';
- if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = '';
- if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = true;
- if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = false;
- populateInterfaceSelect('mangle-val-iniface');
- populateInterfaceSelect('mangle-val-outiface');
- populateAddressListSelect('mangle-val-srclist');
- populateAddressListSelect('mangle-val-dstlist');
- populateGeoIPSelect('mangle-val-srcgeo');
- populateGeoIPSelect('mangle-val-dstgeo');
- allMangleFieldKeys.forEach(k => toggleMangleField(k, false));
- resetMangleCounterDisplay();
- toggleMangleActionFields();
- document.getElementById('mangle-modal').classList.remove('hidden');
- }
- function openEditMangleModal(id) {
- id = decodeURIComponent(id);
- const r = (state.mangleRules || []).find(rule => rule.id === id);
- if (!r) return;
- switchMangleRuleTab('general');
- const badge = document.getElementById('mangle-modal-badge');
- if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
- document.getElementById('mangle-modal-id').value = r.id;
- document.getElementById('mangle-modal-family').value = String(r.ip_version || 4);
- document.getElementById('mangle-modal-enabled').checked = !r.disabled;
- document.getElementById('mangle-modal-comment').value = r.comment || '';
- const mangleChain = r.chain || 'prerouting';
- document.getElementById('mangle-modal-chain').value = mangleChain;
- populateChainDropdown('mangle', mangleChain);
- handleMangleChainChange();
- setFirewallActionSelection('mangle', r.action || 'accept');
-
- if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = r.new_connection_mark || '';
- if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = r.new_routing_mark || '';
- if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = r.new_packet_mark || '';
- if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = r.new_mss || '';
- if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = r.new_dscp != null ? r.new_dscp : '';
- if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = r.new_ttl || '';
- if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = r.new_priority || '';
- if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = r.route || '';
- if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = r.sniff_target || '';
- if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = r.jump_target || '';
- if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = r.address_list || '';
- if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = r.address_list_timeout || '';
- if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
- if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = !!r.log;
- populateInterfaceSelect('mangle-val-iniface', (r.in_interface || '').replace(/^!/, ''));
- populateInterfaceSelect('mangle-val-outiface', (r.out_interface || '').replace(/^!/, ''));
- populateAddressListSelect('mangle-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
- populateAddressListSelect('mangle-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
- populateGeoIPSelect('mangle-val-srcgeo', r.src_geoip || '');
- populateGeoIPSelect('mangle-val-dstgeo', r.dst_geoip || '');
- setMangleFieldVal('src', r.src_address, true);
- setMangleFieldVal('dst', r.dst_address, true);
- setMangleFieldVal('srclist', r.src_address_list, true);
- setMangleFieldVal('dstlist', r.dst_address_list, true);
- setMangleFieldVal('srcgeo', r.src_geoip, true);
- setMangleFieldVal('dstgeo', r.dst_geoip, true);
- if (r.protocol && r.protocol !== 'all') {
- setMangleFieldVal('proto', r.protocol, true);
- } else {
- toggleMangleField('proto', false);
- }
- setMangleFieldVal('sport', r.src_port, true);
- setMangleFieldVal('dport', r.dst_port, true);
- setMangleFieldVal('anyport', r.any_port, true);
- setMangleFieldVal('iniface', r.in_interface, true);
- setMangleFieldVal('outiface', r.out_interface, true);
- setMangleFieldVal('inifacelist', r.in_interface_list, true);
- setMangleFieldVal('outifacelist', r.out_interface_list, true);
- setMangleFieldVal('pktmark', r.packet_mark, true);
- setMangleFieldVal('connmark', r.connection_mark, true);
- setMangleFieldVal('routingmark', r.routing_mark, true);
- setMangleFieldVal('conntype', r.connection_type, false);
- // Connection State
- const states = r.connection_state || [];
- if (states.length > 0) {
- toggleMangleField('cs', true);
- ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
- const el = document.getElementById(`mangle-modal-cs-${s}`);
- if (el) el.checked = states.includes(s);
- });
- } else {
- toggleMangleField('cs', false);
- }
- // Connection NAT State
- const natStates = r.connection_nat_state || [];
- if (natStates.length > 0) {
- toggleMangleField('natstate', true);
- ['srcnat', 'dstnat'].forEach(s => {
- const el = document.getElementById(`mangle-modal-nat-${s}`);
- if (el) el.checked = natStates.includes(s);
- });
- } else {
- toggleMangleField('natstate', false);
- }
- // Advanced tab fields
- setMangleFieldVal('layer7', r.layer7_protocol, false);
- setMangleFieldVal('content', r.content, false);
- setMangleFieldVal('connbytes', r.connection_bytes, false);
- setMangleFieldVal('connrate', r.connection_rate, false);
- setMangleFieldVal('pcc', r.pcc, false);
- setMangleFieldVal('srcmac', r.src_mac_address, true);
- setMangleFieldVal('outbridgeport', r.out_bridge_port, false);
- setMangleFieldVal('inbridgeport', r.in_bridge_port, false);
- setMangleFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
- setMangleFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
- setMangleFieldVal('ipsec', r.ipsec_policy, false);
- setMangleFieldVal('tlshost', r.tls_host, false);
- setMangleFieldVal('ingresspriority', r.ingress_priority, false);
- setMangleFieldVal('priority', r.priority, false);
- setMangleFieldVal('dscp', r.dscp, false);
- setMangleFieldVal('tcpmss', r.tcp_mss, false);
- { const tosEl = document.getElementById('mangle-val-tos'); if (tosEl) tosEl.value = r.tos || ''; }
- setMangleFieldVal('pktsize', r.packet_size, false);
- setMangleFieldVal('random', r.random, false);
- setMangleFieldVal('tcpflags', r.tcp_flags, false);
- setMangleFieldVal('icmpoptions', r.icmp_options, false);
- setMangleFieldVal('ipv4options', r.ipv4_options, false);
- setMangleFieldVal('ttl', r.ttl, false);
- // Extra tab fields
- setMangleFieldVal('nth', r.nth, false);
- setMangleFieldVal('connlimit', r.connection_limit, false);
- setMangleFieldVal('srcaddrtype', r.src_address_type, false);
- setMangleFieldVal('dstaddrtype', r.dst_address_type, false);
- setMangleFieldVal('hotspot', r.hotspot, false);
- setMangleFieldVal('ipfragment', r.ip_fragment, false);
- setMangleFieldVal('limit', r.limit, false);
- setMangleFieldVal('dstlimit', r.dst_limit, false);
- setMangleFieldVal('time', r.time, false);
- setMangleFieldVal('psd', r.psd, false);
- // Action fields
- if (r.jump_target) {
- const jtEl = document.getElementById('mangle-modal-jumptarget');
- if (jtEl) jtEl.value = r.jump_target;
- }
- if (r.address_list) {
- const alEl = document.getElementById('mangle-modal-action-addrlist');
- if (alEl) alEl.value = r.address_list;
- }
- if (r.address_list_timeout) {
- const toEl = document.getElementById('mangle-modal-action-timeout');
- if (toEl) toEl.value = r.address_list_timeout;
- }
- setMangleFieldVal('logprefix', r.log_prefix, false);
- // Statistics
- const bEl = document.getElementById('mangle-stat-bytes');
- const pEl = document.getElementById('mangle-stat-packets');
- if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
- if (pEl) pEl.value = (r.packets || 0).toLocaleString();
- state.mangleLastBytes = r.bytes || 0;
- state.mangleLastPackets = r.packets || 0;
- state.mangleLastTimestamp = Date.now();
- state.mangleStatRateHistory = new Array(30).fill(0);
- state.mangleStatPktHistory = new Array(30).fill(0);
- renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
- renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
- toggleMangleActionFields();
- document.getElementById('mangle-modal').classList.remove('hidden');
- }
- function closeMangleModal() {
- stopMangleStatPolling();
- document.getElementById('mangle-modal').classList.add('hidden');
- }
- function copyMangleRule() {
- document.getElementById('mangle-modal-id').value = '';
- const badge = document.getElementById('mangle-modal-badge');
- if (badge) badge.innerText = 'New...';
- showToast('Rule Cloned', 'Ready to save as a new Mangle rule copy', 'info');
- }
- function resetMangleCounterDisplay() {
- state.mangleStatRateHistory = new Array(30).fill(0);
- state.mangleStatPktHistory = new Array(30).fill(0);
- state.mangleLastBytes = 0;
- state.mangleLastPackets = 0;
- state.mangleLastTimestamp = Date.now();
- const bEl = document.getElementById('mangle-stat-bytes');
- const pEl = document.getElementById('mangle-stat-packets');
- const rEl = document.getElementById('mangle-stat-rate');
- const prEl = document.getElementById('mangle-stat-pktrate');
- if (bEl) bEl.value = '0 B';
- if (pEl) pEl.value = '0';
- if (rEl) rEl.value = '0 bps';
- if (prEl) prEl.value = '0 p/s';
- renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
- renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
- showToast('Counters Reset', 'Mangle rule counter display reset to 0', 'info');
- }
- async function applyMangleRule(closeAfter = false) {
- const id = document.getElementById('mangle-modal-id').value;
- if (!reviewLegacyFirewallSettings('mangle', id)) return;
- const chain = (document.getElementById('mangle-modal-chain').value || '').trim();
- const chainLower = chain.toLowerCase();
- const action = document.getElementById('mangle-modal-action').value;
- const comment = document.getElementById('mangle-modal-comment').value.trim();
- const enabled = document.getElementById('mangle-modal-enabled').checked;
- const src = getMangleFieldVal('src', true);
- const dst = getMangleFieldVal('dst', true);
- const srclist = getMangleFieldVal('srclist', true);
- const dstlist = getMangleFieldVal('dstlist', true);
- const srcgeo = getMangleFieldVal('srcgeo', true);
- const dstgeo = getMangleFieldVal('dstgeo', true);
- const proto = getMangleFieldVal('proto', true);
- const sport = getMangleFieldVal('sport', true);
- const dport = getMangleFieldVal('dport', true);
- const anyport = getMangleFieldVal('anyport', true);
- if ((sport || dport || anyport) && !['tcp', 'udp'].includes(proto)) {
- switchMangleRuleTab('general'); toggleMangleField('proto', true);
- showToast('Select protocol', 'Port matches require TCP or UDP without protocol inversion.', 'error'); document.getElementById('mangle-val-proto').focus(); return;
- }
- let iniface = getMangleFieldVal('iniface', true);
- let outiface = getMangleFieldVal('outiface', true);
- let inifacelist = getMangleFieldVal('inifacelist', true);
- let outifacelist = getMangleFieldVal('outifacelist', true);
- if (chainLower === 'prerouting' || chainLower === 'input') {
- outiface = '';
- outifacelist = '';
- } else if (chainLower === 'output' || chainLower === 'postrouting') {
- iniface = '';
- inifacelist = '';
- }
- if (!chain) { switchMangleRuleTab('general'); showToast('Mangle rule', 'Enter a chain.', 'error'); document.getElementById('mangle-modal-chain').focus(); return; }
- if (action === 'set-priority' && chainLower !== 'postrouting') {
- switchMangleRuleTab('general');
- showToast('Invalid Target for Chain', 'CLASSIFY (set-priority) requires POSTROUTING chain in iptables.', 'error');
- return;
- }
- const pktmark = getMangleFieldVal('pktmark', true);
- const connmark = getMangleFieldVal('connmark', true);
- const routingmark = getMangleFieldVal('routingmark', true);
- const conntype = getMangleFieldVal('conntype', false);
- const states = [];
- const csBox = document.getElementById('mangle-field-cs');
- if (csBox && !csBox.classList.contains('hidden')) {
- ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
- if (document.getElementById(`mangle-modal-cs-${s}`)?.checked) states.push(s);
- });
- }
- const natStates = [];
- const natBox = document.getElementById('mangle-field-natstate');
- if (natBox && !natBox.classList.contains('hidden')) {
- ['srcnat', 'dstnat'].forEach(s => {
- if (document.getElementById(`mangle-modal-nat-${s}`)?.checked) natStates.push(s);
- });
- }
- const payload = {
- ip_version: Number(document.getElementById('mangle-modal-family').value),
- id,
- chain,
- action,
- protocol: proto || 'all',
- src_address: src,
- dst_address: dst,
- src_port: sport,
- dst_port: dport,
- any_port: anyport,
- in_interface: iniface,
- out_interface: outiface,
- in_interface_list: inifacelist,
- out_interface_list: outifacelist,
- packet_mark: pktmark,
- connection_mark: connmark,
- routing_mark: routingmark,
- connection_type: conntype,
- connection_state: states,
- connection_nat_state: natStates,
- src_address_list: srclist,
- dst_address_list: dstlist,
- src_geoip: srcgeo,
- dst_geoip: dstgeo,
- comment,
- disabled: !enabled,
- // Advanced tab
- content: getMangleFieldVal('content', false),
- src_mac_address: (chainLower === 'output' || chainLower === 'postrouting') ? '' : getMangleFieldVal('srcmac', true),
- out_bridge_port: (chainLower === 'input' || chainLower === 'prerouting') ? '' : getMangleFieldVal('outbridgeport', false),
- in_bridge_port: (chainLower === 'output' || chainLower === 'postrouting') ? '' : getMangleFieldVal('inbridgeport', false),
- ipsec_policy: getMangleFieldVal('ipsec', false),
- dscp: getMangleFieldVal('dscp', false),
- tcp_mss: getMangleFieldVal('tcpmss', false),
- tos: document.getElementById('mangle-val-tos')?.value || '',
- packet_size: getMangleFieldVal('pktsize', false),
- random: getMangleFieldVal('random', false),
- tcp_flags: getMangleFieldVal('tcpflags', false),
- icmp_options: getMangleFieldVal('icmpoptions', false),
- ttl: getMangleFieldVal('ttl', false),
- // Extra tab
- nth: getMangleFieldVal('nth', false),
- connection_limit: getMangleFieldVal('connlimit', false),
- src_address_type: getMangleFieldVal('srcaddrtype', false),
- dst_address_type: getMangleFieldVal('dstaddrtype', false),
- ip_fragment: getMangleFieldVal('ipfragment', false),
- limit: getMangleFieldVal('limit', false),
- time: getMangleFieldVal('time', false),
- // Action tab
- new_connection_mark: action === 'mark-connection' ? (document.getElementById('mangle-modal-newconnmark')?.value.trim() || '') : '',
- new_routing_mark: action === 'mark-routing' ? (document.getElementById('mangle-modal-newroutingmark')?.value.trim() || '') : '',
- new_packet_mark: action === 'mark-packet' ? (document.getElementById('mangle-modal-newpktmark')?.value.trim() || '') : '',
- new_mss: action === 'change-mss' ? (document.getElementById('mangle-modal-newmss')?.value.trim() || '') : '',
- new_dscp: action === 'change-dscp' ? parseInt(document.getElementById('mangle-modal-newdscp')?.value || '0', 10) : 0,
- new_ttl: action === 'change-ttl' ? (document.getElementById('mangle-modal-newttl')?.value.trim() || '') : '',
- new_priority: action === 'set-priority' ? (document.getElementById('mangle-modal-newpriority')?.value.trim() || '') : '',
- passthrough: document.getElementById('mangle-modal-passthrough')?.checked ?? true,
- jump_target: action === 'jump' ? (document.getElementById('mangle-modal-jumptarget')?.value || '') : '',
- address_list: action.includes('address') ? (document.getElementById('mangle-modal-action-addrlist')?.value || '') : '',
- address_list_timeout: action.includes('address') ? (document.getElementById('mangle-modal-action-timeout')?.value || '') : '',
- log: document.getElementById('mangle-modal-log')?.checked || false,
- log_prefix: getMangleFieldVal('logprefix', false)
- };
- try {
- const res = await fetch(`${API_BASE}/firewall/mangle`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(payload)
- });
- if (res.ok) {
- const data = await res.json();
- showToast('Mangle Rule Saved', 'Marking rule updated', 'success');
- loadFirewall(false);
- if (closeAfter) {
- closeMangleModal();
- } else {
- if (data.id) {
- document.getElementById('mangle-modal-id').value = data.id;
- const badge = document.getElementById('mangle-modal-badge');
- if (badge) badge.innerText = `#${data.id}`;
- }
- }
- } else {
- const err = await res.json();
- showToast('Error', err.message || 'Failed to save mangle rule', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- function submitSaveMangleRule(e) {
- if (e && e.preventDefault) e.preventDefault();
- return applyMangleRule(true);
- }
- function startMangleStatPolling() {
- stopMangleStatPolling();
- pollMangleRuleStats();
- state.mangleStatInterval = setInterval(pollMangleRuleStats, 1000);
- }
- function stopMangleStatPolling() {
- if (state.mangleStatInterval) {
- clearInterval(state.mangleStatInterval);
- state.mangleStatInterval = null;
- }
- }
- async function pollMangleRuleStats() {
- const id = document.getElementById('mangle-modal-id')?.value;
- if (!id) {
- renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory || new Array(30).fill(0), 'bps', 'mangle-stat-legend-rate');
- renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory || new Array(30).fill(0), 'p/s', 'mangle-stat-legend-pktrate');
- return;
- }
- try {
- const res = await fetch(`${API_BASE}/firewall/mangle`);
- if (!res.ok) return;
- const rules = await res.json();
- const r = rules.find(x => x.id === id);
- if (!r) return;
- const now = Date.now();
- const dt = Math.max(0.2, (now - (state.mangleLastTimestamp || now)) / 1000);
- state.mangleLastTimestamp = now;
- const curBytes = r.bytes || 0;
- const curPackets = r.packets || 0;
- const deltaBytes = Math.max(0, curBytes - (state.mangleLastBytes ?? curBytes));
- const deltaPkts = Math.max(0, curPackets - (state.mangleLastPackets ?? curPackets));
- state.mangleLastBytes = curBytes;
- state.mangleLastPackets = curPackets;
- const rateBps = Math.round((deltaBytes * 8) / dt);
- const ratePkt = Math.round(deltaPkts / dt);
- if (!state.mangleStatRateHistory) state.mangleStatRateHistory = new Array(30).fill(0);
- if (!state.mangleStatPktHistory) state.mangleStatPktHistory = new Array(30).fill(0);
- state.mangleStatRateHistory.push(rateBps);
- if (state.mangleStatRateHistory.length > 30) state.mangleStatRateHistory.shift();
- state.mangleStatPktHistory.push(ratePkt);
- if (state.mangleStatPktHistory.length > 30) state.mangleStatPktHistory.shift();
- const bEl = document.getElementById('mangle-stat-bytes');
- const pEl = document.getElementById('mangle-stat-packets');
- const rEl = document.getElementById('mangle-stat-rate');
- const prEl = document.getElementById('mangle-stat-pktrate');
- if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
- if (pEl) pEl.value = curPackets.toLocaleString();
- if (rEl) rEl.value = formatBps(rateBps);
- if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
- renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
- renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
- } catch (e) {
- console.error('Error polling Mangle rule stats', e);
- }
- }
- async function moveMangleRule(id, dir) {
- id = decodeURIComponent(id);
- try {
- const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ direction: dir })
- });
- if (!res.ok) throw new Error(await responseError(res));
- await loadFirewall(false);
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function toggleMangleRuleState(id, disabled) {
- id = decodeURIComponent(id);
- try {
- const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ disabled })
- });
- if (!res.ok) throw new Error(await responseError(res));
- await loadFirewall(false);
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deleteMangleRule(id) {
- id = decodeURIComponent(id);
- if (!confirm('Are you sure you want to delete this mangle rule?')) return;
- try {
- const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
- if (!res.ok) throw new Error(await responseError(res));
- {
- showToast('Deleted', 'Mangle rule removed', 'success');
- loadFirewall(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // ----------------- Address Lists -----------------
- function renderAddressLists() {
- const filterList = document.getElementById('addrlist-filter-name')?.value || '';
- const tbody = document.getElementById('addrlist-table-body');
- const empty = document.getElementById('addrlist-empty');
- if (!tbody) return;
- tbody.innerHTML = '';
- const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
- document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries${entries.filter(e => e.dynamic).length >= 2000 ? ' (dynamic results capped at 2000)' : ''}`;
- // Update filter select
- const sel = document.getElementById('addrlist-filter-name');
- if (sel) {
- const cur = sel.value;
- sel.innerHTML = '<option value="">All Lists</option>';
- const set = new Set((state.addressLists || []).map(a => a.name));
- set.forEach(n => {
- const opt = document.createElement('option');
- opt.value = n;
- opt.innerText = n;
- if (n === cur) opt.selected = true;
- sel.appendChild(opt);
- });
- }
- if (entries.length === 0) {
- empty?.classList.remove('hidden');
- return;
- }
- empty?.classList.add('hidden');
- entries.forEach((raw, idx) => {
- const e = safeFirewallRow(raw);
- const tr = document.createElement('tr');
- tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
- if (!e.dynamic) tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
- tr.innerHTML = `
- <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
- <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>
- <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
- <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
- <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]">${e.dynamic ? 'Dynamic · '+(e.timeout ? e.timeout+'s remaining' : 'no expiry') : e.comment || '-'}</td>
- <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
- ${e.dynamic ? '' : ` <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>
- <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
- `}
- <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
- </td>
- `;
- tbody.appendChild(tr);
- });
- populateCommonAddrListDatalist();
- }
- function openAddAddrListModal() {
- document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
- document.getElementById('addrlist-modal-id').value = '';
- document.getElementById('addrlist-modal-name').value = '';
- document.getElementById('addrlist-modal-addr').value = '';
- document.getElementById('addrlist-modal-comment').value = '';
- document.getElementById('addrlist-modal-disabled').checked = false;
- const submitBtn = document.getElementById('addrlist-modal-submit-btn');
- if (submitBtn) submitBtn.innerText = 'Add to List';
- document.getElementById('addrlist-modal').classList.remove('hidden');
- }
- function openEditAddrListModal(id) {
- id = decodeURIComponent(id);
- const e = (state.addressLists || []).find(item => item.id === id);
- if (!e) return;
- document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
- document.getElementById('addrlist-modal-id').value = e.id;
- document.getElementById('addrlist-modal-name').value = e.name;
- document.getElementById('addrlist-modal-addr').value = e.address;
- document.getElementById('addrlist-modal-comment').value = e.comment || '';
- document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
- const submitBtn = document.getElementById('addrlist-modal-submit-btn');
- if (submitBtn) submitBtn.innerText = 'Save Changes';
- document.getElementById('addrlist-modal').classList.remove('hidden');
- }
- function closeAddrListModal() {
- document.getElementById('addrlist-modal').classList.add('hidden');
- }
- async function submitSaveAddrList(e) {
- e.preventDefault();
- const id = document.getElementById('addrlist-modal-id').value;
- const name = document.getElementById('addrlist-modal-name').value.trim();
- const addr = document.getElementById('addrlist-modal-addr').value.trim();
- const comment = document.getElementById('addrlist-modal-comment').value.trim();
- const disabled = document.getElementById('addrlist-modal-disabled').checked;
- try {
- const res = await fetch(`${API_BASE}/firewall/address-lists`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ id, name, address: addr, comment, disabled })
- });
- if (res.ok) {
- showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
- closeAddrListModal();
- loadFirewall(false);
- } else {
- const err = await res.json();
- showToast('Error', err.message || 'Failed to save address list', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function toggleAddrListState(id, disabled) {
- id = decodeURIComponent(id);
- try {
- const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ disabled })
- });
- if (res.ok) {
- loadFirewall(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deleteAddrList(id) {
- id = decodeURIComponent(id);
- if (!confirm('Are you sure you want to delete this address list item?')) return;
- try {
- const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
- if (res.ok) {
- showToast('Deleted', 'Address list item removed', 'info');
- loadFirewall(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // ----------------- Geo-Location IP Management -----------------
- async function loadGeoIP() {
- try {
- const [statusRes, countriesRes] = await Promise.all([
- fetch(`${API_BASE}/firewall/geoip/status`),
- fetch(`${API_BASE}/firewall/geoip/countries`)
- ]);
- if (statusRes.ok) state.geoStatus = await statusRes.json();
- if (countriesRes.ok) state.geoCountries = await countriesRes.json();
- updateGeoHeader();
- renderGeoCountries();
- } catch (err) {
- console.error('Failed to load GeoIP:', err);
- }
- }
- function getGeoUsageMap() {
- const usage = {};
- const checkRule = (r, type) => {
- ['src_geoip', 'dst_geoip'].forEach(field => {
- let val = (r && r[field]) || '';
- let code = val.replace(/^!/, '').replace(/^geo:/, '').replace(/^geo_/, '').toUpperCase().trim();
- if (code) {
- if (!usage[code]) usage[code] = [];
- const label = `${type} #${r.priority !== undefined ? r.priority : (r.id || '')}`;
- if (!usage[code].includes(label)) usage[code].push(label);
- }
- });
- };
- (state.filterRules || []).forEach(r => checkRule(r, 'Filter'));
- (state.natRules || []).forEach(r => checkRule(r, 'NAT'));
- (state.mangleRules || []).forEach(r => checkRule(r, 'Mangle'));
- return usage;
- }
- function updateGeoHeader() {
- const s = state.geoStatus || {};
- const statusBadge = document.getElementById('geo-status-badge');
- if (statusBadge) {
- statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
- statusBadge.className = s.auto_update
- ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
- : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
- }
- const intervalLabel = document.getElementById('geo-interval-label');
- if (intervalLabel) {
- intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
- }
- const usageMap = getGeoUsageMap();
- const inUseCount = Object.keys(usageMap).length;
- const activeCountEl = document.getElementById('geo-stat-active-countries');
- if (activeCountEl) activeCountEl.innerText = inUseCount.toLocaleString();
- const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
- if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
- const lastSyncEl = document.getElementById('geo-stat-last-sync');
- if (lastSyncEl) {
- if (s.last_updated && !s.last_updated.startsWith('0001')) {
- const d = new Date(s.last_updated);
- lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
- } else {
- lastSyncEl.innerText = 'Never (Sync Pending)';
- }
- }
- const nextSyncEl = document.getElementById('geo-stat-next-sync');
- if (nextSyncEl) {
- if (s.next_update && !s.next_update.startsWith('0001')) {
- const d = new Date(s.next_update);
- nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
- } else {
- nextSyncEl.innerText = '-';
- }
- }
- const badge = document.getElementById('fw-badge-geo');
- if (badge) badge.innerText = inUseCount || (state.geoCountries || []).filter(c => c.subnet_count > 0).length || 0;
- }
- function renderGeoCountries() {
- const tbody = document.getElementById('geo-table-body');
- const empty = document.getElementById('geo-empty');
- if (!tbody) return;
- tbody.innerHTML = '';
- const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
- const continent = document.getElementById('geo-continent-filter')?.value || '';
- const inUseOnly = document.getElementById('geo-filter-inuse-only')?.checked;
- const cachedOnly = document.getElementById('geo-filter-cached-only')?.checked;
- const usageMap = getGeoUsageMap();
- const countries = (state.geoCountries || []).filter(c => {
- const isUsed = !!usageMap[c.code];
- if (inUseOnly && !isUsed) return false;
- if (cachedOnly && (!c.subnet_count || c.subnet_count === 0)) return false;
- if (continent && c.continent !== continent) return false;
- if (q) {
- const matchCode = c.code.toLowerCase().includes(q);
- const matchName = c.name.toLowerCase().includes(q);
- if (!matchCode && !matchName) return false;
- }
- return true;
- });
- if (countries.length === 0) {
- empty?.classList.remove('hidden');
- return;
- }
- empty?.classList.add('hidden');
- countries.forEach(c => {
- const tr = document.createElement('tr');
- const isUsed = !!usageMap[c.code];
- const rulesUsing = usageMap[c.code] || [];
- tr.className = `hover:bg-slate-800/40 transition text-xs ${isUsed ? 'bg-emerald-950/20' : ''}`;
- let statusHtml = '';
- if (isUsed) {
- 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>`;
- } else if (c.subnet_count > 0) {
- 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>';
- } else {
- statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-slate-500 bg-slate-800/60">READY</span>';
- }
- tr.innerHTML = `
- <td class="py-2.5 px-3 text-center">
- <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'}">
- ${c.code}
- </span>
- </td>
- <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
- <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
- <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
- ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
- </td>
- <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
- <td class="py-2.5 px-3">
- ${statusHtml}
- </td>
- <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
- <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>
- <button onclick="viewGeoSubnets('${c.code}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
- </td>
- `;
- tbody.appendChild(tr);
- });
- }
- function quickFilterGeo(preset) {
- const searchInput = document.getElementById('geo-search-input');
- const continentSel = document.getElementById('geo-continent-filter');
- const inUseCheck = document.getElementById('geo-filter-inuse-only');
- const cachedCheck = document.getElementById('geo-filter-cached-only');
- if (searchInput) searchInput.value = '';
- if (continentSel) continentSel.value = '';
- if (inUseCheck) inUseCheck.checked = false;
- if (cachedCheck) cachedCheck.checked = false;
- if (preset === 'GR') {
- if (searchInput) searchInput.value = 'Greece';
- } else if (preset === 'Europe') {
- if (continentSel) continentSel.value = 'Europe';
- } else if (preset === 'HIGHRISK') {
- if (searchInput) searchInput.value = 'China';
- }
- renderGeoCountries();
- }
- async function toggleGeoCountry(code, enabled) {
- try {
- const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ enabled })
- });
- if (res.ok) {
- showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
- loadGeoIP();
- } else {
- const err = await res.json();
- showToast('Error', err.message || 'Failed to toggle country', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function updateGeoCountry(code) {
- try {
- showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
- const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
- if (res.ok) {
- const data = await res.json();
- showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
- loadGeoIP();
- } else {
- const err = await res.json();
- showToast('Sync Error', err.message || 'Failed to sync country', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function triggerGeoUpdateNow() {
- const spinner = document.getElementById('geo-update-spinner');
- if (spinner) spinner.classList.remove('hidden');
- try {
- const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
- if (res.ok) {
- showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
- setTimeout(() => {
- loadGeoIP();
- if (spinner) spinner.classList.add('hidden');
- }, 2500);
- } else {
- const err = await res.json();
- showToast('Notice', err.message || 'Update in progress', 'info');
- if (spinner) spinner.classList.add('hidden');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- if (spinner) spinner.classList.add('hidden');
- }
- }
- async function applyGeoPreset(preset) {
- try {
- const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
- });
- if (res.ok) {
- showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
- loadGeoIP();
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- function openGeoIntervalModal() {
- const s = state.geoStatus || {};
- document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
- const sel = document.getElementById('geo-cfg-interval');
- const customBox = document.getElementById('geo-cfg-custom-box');
- const customHoursInput = document.getElementById('geo-cfg-custom-hours');
- const curHours = s.interval_hours || 24;
- const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
- if (matchOption) {
- sel.value = String(curHours);
- customBox.classList.add('hidden');
- } else {
- sel.value = 'custom';
- customHoursInput.value = curHours;
- customBox.classList.remove('hidden');
- }
- document.getElementById('geo-interval-modal').classList.remove('hidden');
- }
- function closeGeoIntervalModal() {
- document.getElementById('geo-interval-modal').classList.add('hidden');
- }
- function toggleCustomGeoInterval() {
- const val = document.getElementById('geo-cfg-interval').value;
- const customBox = document.getElementById('geo-cfg-custom-box');
- if (val === 'custom') {
- customBox.classList.remove('hidden');
- } else {
- customBox.classList.add('hidden');
- }
- }
- async function submitGeoIntervalSettings(e) {
- e.preventDefault();
- const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
- const intervalVal = document.getElementById('geo-cfg-interval').value;
- let hours = 24;
- if (intervalVal === 'custom') {
- hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
- } else {
- hours = parseInt(intervalVal, 10) || 24;
- }
- try {
- const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
- });
- if (res.ok) {
- showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
- closeGeoIntervalModal();
- loadGeoIP();
- } else {
- const err = await res.json();
- showToast('Error', err.message || 'Failed to save schedule', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function viewGeoSubnets(code, name) {
- if (!name) {
- const found = (state.geoCountries || []).find(x => x.code === code);
- name = found ? found.name : code;
- }
- document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
- document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
- const listEl = document.getElementById('geo-subnets-list');
- listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
- document.getElementById('geo-subnets-modal').classList.remove('hidden');
- try {
- const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
- if (res.ok) {
- const data = await res.json();
- const subnets = data.subnets || [];
- if (subnets.length === 0) {
- listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
- } else {
- listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
- }
- } else {
- listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
- }
- } catch (err) {
- listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
- }
- }
- function closeGeoSubnetsModal() {
- document.getElementById('geo-subnets-modal').classList.add('hidden');
- }
- // ----------------- Active Connections Tracking -----------------
- async function loadConnections() {
- try {
- const res = await fetch(`${API_BASE}/firewall/connections`);
- const data = await res.json();
- if (!res.ok) throw new Error(data.message || 'Connection tracking unavailable');
- state.connections = Array.isArray(data) ? data : [];
- document.getElementById('fw-badge-connections').innerText = state.connections.length;
- document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
- renderConnections();
- } catch (err) {
- console.error('Failed to load connections:', err);
- const badge=document.getElementById('conns-count-badge'); if(badge) badge.textContent='Unavailable: '+err.message;
- }
- }
- function renderConnections() {
- const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
- const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
- const tbody = document.getElementById('conns-table-body');
- const empty = document.getElementById('conns-empty');
- if (!tbody) return;
- tbody.innerHTML = '';
- const conns = (state.connections || []).filter(c => {
- if (protoFilter && c.protocol !== protoFilter) return false;
- if (search) {
- const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
- if (!line.includes(search)) return false;
- }
- return true;
- });
- if (conns.length === 0) {
- empty?.classList.remove('hidden');
- return;
- }
- empty?.classList.add('hidden');
- conns.slice(0, 150).forEach(c => {
- const tr = document.createElement('tr');
- tr.className = 'hover:bg-slate-800/40 transition text-xs';
- let stateColor = 'text-slate-400';
- if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
- else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
- tr.innerHTML = `
- <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
- <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
- <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
- <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>
- <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>
- <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
- <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
- <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
- <td class="py-2.5 px-3 text-right font-sans">
- ${['TCP','UDP','SCTP','DCCP','ICMP','ICMPV6'].includes(c.protocol) ? ` <button onclick="killConnection('${c.protocol}', '${c.src_address}', ${c.src_port}, '${c.dst_address}', ${c.dst_port}, ${c.ip_version || 4}, ${c.zone || 0}, ${c.icmp_id ?? 'null'}, ${c.icmp_type ?? 'null'}, ${c.icmp_code ?? 'null'})" class="text-xs text-rose-400 hover:text-rose-300">Kill</button>` : ''}
- </td>
- `;
- tbody.appendChild(tr);
- });
- }
- async function killConnection(protocol, src, sport, dst, dport, ip_version, zone, icmp_id, icmp_type, icmp_code) {
- try {
- const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ protocol, src, sport, dst, dport, ip_version, zone, icmp_id, icmp_type, icmp_code })
- });
- if (res.ok) {
- showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
- loadConnections();
- } else { const error = await res.json(); showToast('Error', error.message || 'Unable to terminate this flow', 'error'); }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function resetFirewallCounters() {
- if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
- try {
- const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
- if (res.ok) {
- showToast('Counters Reset', 'All rules counters reset to 0', 'success');
- loadFirewall(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
- function switchRoutesSubTab(tab) {
- state.routesSubTab = tab;
- const tabs = ['routes', 'rules', 'tables'];
- tabs.forEach(t => {
- const panel = document.getElementById(`routes-subtab-${t}`);
- const btn = document.getElementById(`routes-subtab-btn-${t}`);
- if (panel) {
- if (t === tab) panel.classList.remove('hidden');
- else panel.classList.add('hidden');
- }
- if (btn) {
- if (t === tab) {
- 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';
- } else {
- 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';
- }
- }
- });
- setTimeout(initTableSorting, 50);
- }
- async function loadRoutes() {
- try {
- const [routesRes, rulesRes, tablesRes] = await Promise.all([
- fetch(`${API_BASE}/routes`),
- fetch(`${API_BASE}/routing/rules`),
- fetch(`${API_BASE}/routing/tables`)
- ]);
- if (routesRes.ok) state.routes = await routesRes.json();
- if (rulesRes.ok) state.policyRules = await rulesRes.json();
- if (tablesRes.ok) state.routingTables = await tablesRes.json();
- const bRoutes = document.getElementById('routes-badge-routes');
- if (bRoutes) bRoutes.innerText = (state.routes || []).length;
- const showSystem = document.getElementById('prule-show-system')?.checked;
- const userRules = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
- const bRules = document.getElementById('routes-badge-rules');
- if (bRules) bRules.innerText = userRules.length;
- const bTables = document.getElementById('routes-badge-tables');
- if (bTables) bTables.innerText = (state.routingTables || []).length;
- const bRoutesCount = document.getElementById('badge-routes-count');
- if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
- renderRoutesList();
- renderPolicyRules();
- renderRoutingTables();
- } catch (err) {
- console.error('Failed to load routing:', err);
- }
- }
- function getRouteProtocolBadge(proto) {
- const p = (proto || 'static').toLowerCase();
- switch (p) {
- case 'bgp':
- return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-amber-500/20 text-amber-300 border border-amber-500/30">bgp</span>`;
- case 'ibgp':
- return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-yellow-500/20 text-yellow-300 border border-yellow-500/30">ibgp</span>`;
- case 'ospf':
- return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-emerald-500/20 text-emerald-300 border border-emerald-500/30">ospf</span>`;
- case 'rip':
- return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-orange-500/20 text-orange-300 border border-orange-500/30">rip</span>`;
- case 'static':
- return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-blue-500/20 text-blue-300 border border-blue-500/30">static</span>`;
- case 'connected':
- return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-slate-800 text-slate-300 border border-slate-700">connected</span>`;
- case 'dhcp':
- return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-cyan-500/20 text-cyan-300 border border-cyan-500/30">dhcp</span>`;
- case 'multicast':
- return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-purple-500/20 text-purple-300 border border-purple-500/30">igmp</span>`;
- default:
- return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-slate-800 text-slate-400 border border-slate-700">${escapeHtml(p)}</span>`;
- }
- }
- function renderRoutesList() {
- const tableFilter = document.getElementById('routes-filter-table')?.value || '';
- const typeFilter = document.getElementById('routes-filter-type')?.value || '';
- const tbody = document.getElementById('routes-table-body');
- const empty = document.getElementById('routes-empty');
- if (!tbody) return;
- // Update table filter select
- const sel = document.getElementById('routes-filter-table');
- if (sel) {
- const cur = sel.value;
- sel.innerHTML = '<option value="">All Tables</option>';
- (state.routingTables || []).forEach(t => {
- const opt = document.createElement('option');
- opt.value = t.name;
- opt.innerText = t.name;
- if (t.name === cur) opt.selected = true;
- sel.appendChild(opt);
- });
- }
- const routes = (state.routes || []).filter(r => {
- if (tableFilter && r.routing_table !== tableFilter) return false;
- if (typeFilter === 'ecmp' && !r.ecmp) return false;
- if (typeFilter === 'multicast' && !r.multicast) return false;
- if (typeFilter === 'static' && !r.static) return false;
- if (typeFilter === 'dynamic' && !r.dynamic) return false;
- if (typeFilter === 'connected' && !r.connect) return false;
- if (typeFilter === 'bgp' && (r.protocol || '').toLowerCase() !== 'bgp' && (r.protocol || '').toLowerCase() !== 'ibgp') return false;
- if (typeFilter === 'ospf' && (r.protocol || '').toLowerCase() !== 'ospf') return false;
- if (typeFilter === 'dhcp' && (r.protocol || '').toLowerCase() !== 'dhcp') return false;
- return true;
- });
- const ecmpCount = (state.routes || []).filter(r => r.ecmp).length;
- const mcCount = (state.routes || []).filter(r => r.multicast).length;
- let summaryText = `${routes.length} Routes`;
- if (ecmpCount > 0) summaryText += ` • ${ecmpCount} ECMP`;
- if (mcCount > 0) summaryText += ` • ${mcCount} Multicast/IGMP`;
- const badgeEl = document.getElementById('routes-count-badge');
- if (badgeEl) badgeEl.innerText = summaryText;
- if (routes.length === 0) {
- empty?.classList.remove('hidden');
- tbody.innerHTML = '';
- return;
- }
- empty?.classList.add('hidden');
- const sig = `${tableFilter}|${typeFilter}|` + routes.map(r => `${r.id}:${r.active}:${r.disabled}:${r.distance}:${r.protocol}:${r.health_status}:${(r.health_rtt_ms || 0).toFixed(0)}`).join(';');
- if (tbody.dataset.sig === sig) {
- return; // Routes table unchanged! Do not wipe DOM or flicker!
- }
- tbody.dataset.sig = sig;
- tbody.innerHTML = '';
- routes.forEach(r => {
- const tr = document.createElement('tr');
- tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
- tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
- // Routing Flags string: D=Dynamic, A=Active, C=Connect, S=Static, E=ECMP, M=Multicast, X=Disabled
- let flags = '';
- if (r.dynamic) flags += 'D';
- if (r.active) flags += 'A';
- if (r.connect) flags += 'C';
- if (r.static) flags += 'S';
- if (r.ecmp) flags += 'E';
- if (r.multicast) flags += 'M';
- if (r.disabled) flags += 'X';
- const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
- let healthCell = `<span class="text-slate-600 font-mono text-[11px]">-</span>`;
- if (r.check_gateway === 'internet') {
- if (r.health_status === 'online') {
- const ms = (r.health_rtt_ms || 0).toFixed(0);
- healthCell = `
- <span class="px-2 py-0.5 rounded text-[10px] font-mono bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 font-semibold inline-flex items-center gap-1.5" title="Internet Verified via ${escapeHtml(r.check_target || '1.1.1.1')} (${r.health_loss_pct || 0}% loss)">
- <span class="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></span>
- <span>Internet OK (${ms}ms)</span>
- </span>
- `;
- } else if (r.health_status === 'offline') {
- healthCell = `
- <span class="px-2 py-0.5 rounded text-[10px] font-mono bg-rose-500/20 text-rose-300 border border-rose-500/40 font-bold inline-flex items-center gap-1.5 animate-pulse" title="Internet probe to ${escapeHtml(r.check_target || '1.1.1.1')} failed! Route withdrawn for failover.">
- <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
- <span>Internet Down</span>
- </span>
- `;
- } else {
- healthCell = `
- <span class="px-2 py-0.5 rounded text-[10px] font-mono bg-slate-800 text-slate-400 border border-slate-700 inline-flex items-center gap-1.5">
- <span class="w-1.5 h-1.5 rounded-full bg-amber-400 animate-ping"></span>
- <span>Checking...</span>
- </span>
- `;
- }
- } else if (r.check_gateway === 'ping') {
- if (r.health_status === 'online') {
- healthCell = `
- <span class="px-2 py-0.5 rounded text-[10px] font-mono bg-cyan-500/20 text-cyan-300 border border-cyan-500/30 font-semibold inline-flex items-center gap-1.5">
- <span class="w-1.5 h-1.5 rounded-full bg-cyan-400"></span>
- <span>Gateway OK (${(r.health_rtt_ms || 0).toFixed(0)}ms)</span>
- </span>
- `;
- } else if (r.health_status === 'offline') {
- healthCell = `
- <span class="px-2 py-0.5 rounded text-[10px] font-mono bg-rose-500/20 text-rose-300 border border-rose-500/40 font-bold inline-flex items-center gap-1.5">
- <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
- <span>Gateway Dead</span>
- </span>
- `;
- }
- }
- const flagDescriptions = [];
- if (r.dynamic) flagDescriptions.push('Dynamic (D)');
- if (r.active) flagDescriptions.push('Active (A)');
- if (r.connect) flagDescriptions.push('Connected (C)');
- if (r.static) flagDescriptions.push('Static (S)');
- if (r.ecmp) flagDescriptions.push('ECMP - Equal-Cost Multi-Path (E)');
- if (r.multicast) flagDescriptions.push('Multicast / IGMP Group (M)');
- if (r.disabled) flagDescriptions.push('Disabled (X)');
- tr.innerHTML = `
- <td class="py-2.5 px-3 text-center">
- <span class="px-1.5 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 ${
- r.active ? (r.ecmp ? 'text-purple-300 border border-purple-500/40' : (r.multicast ? 'text-amber-300 border border-amber-500/40' : 'text-cyan-400 border border-cyan-800/40')) : (r.health_status === 'offline' ? 'text-rose-400 border border-rose-800/40' : 'text-slate-500')
- }" title="Flags: ${flagDescriptions.join(', ')}">
- ${flags || '-'}
- </span>
- </td>
- <td class="py-2.5 px-3">
- <div class="flex items-center gap-1.5 flex-wrap">
- <span class="font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${escapeHtml(r.dst_address)}</span>
- ${r.ecmp ? `
- <span class="px-1.5 py-0.2 rounded text-[9px] font-mono font-bold bg-purple-500/20 text-purple-300 border border-purple-500/30 inline-flex items-center gap-1" title="Equal-Cost Multi-Path (ECMP / Multi-gateway)">
- <span>⚡ ECMP</span>
- </span>
- ` : ''}
- ${r.multicast ? `
- <span class="px-1.5 py-0.2 rounded text-[9px] font-mono font-bold bg-amber-500/20 text-amber-300 border border-amber-500/30 inline-flex items-center gap-1" title="Multicast / IGMP Group Route">
- <span>IGMP</span>
- </span>
- ` : ''}
- </div>
- </td>
- <td class="py-2.5 px-3">${getRouteProtocolBadge(r.protocol)}</td>
- <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>
- <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
- <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
- <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
- <td class="py-2.5 px-3">${healthCell}</td>
- <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
- <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
- ${r.static ? `
- <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>
- <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
- <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
- ` : `
- <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
- `}
- </td>
- `;
- tbody.appendChild(tr);
- });
- }
- function openAddRouteModal() {
- document.getElementById('route-modal-title').innerText = 'Add Static Route';
- document.getElementById('route-modal-id').value = '';
- document.getElementById('route-modal-old-dst').value = '';
- document.getElementById('route-modal-old-gw').value = '';
- document.getElementById('route-modal-old-distance').value = '';
- document.getElementById('route-modal-old-table').value = '';
- document.getElementById('route-modal-old-iface').value = '';
- const dstInput = document.getElementById('route-modal-dst');
- const gwInput = document.getElementById('route-modal-gw');
- const distInput = document.getElementById('route-modal-distance');
- const ifaceSelect = document.getElementById('route-modal-iface');
- const tableSelect = document.getElementById('route-modal-table');
- const commentInput = document.getElementById('route-modal-comment');
- const disCheck = document.getElementById('route-modal-disabled');
- const saveBtn = document.querySelector('#route-modal button[type="submit"]');
- dstInput.disabled = false;
- dstInput.value = '0.0.0.0/0';
- gwInput.disabled = false;
- gwInput.value = '';
- distInput.disabled = false;
- distInput.value = '1';
- ifaceSelect.disabled = false;
- tableSelect.disabled = false;
- commentInput.disabled = false;
- commentInput.value = '';
- disCheck.disabled = false;
- disCheck.checked = false;
- if (saveBtn) saveBtn.classList.remove('hidden');
- const checkGw = document.getElementById('route-modal-check-gw');
- if (checkGw) checkGw.value = 'internet';
- const checkTarget = document.getElementById('route-modal-check-target');
- if (checkTarget) checkTarget.value = '1.1.1.1';
- const checkInterval = document.getElementById('route-modal-check-interval');
- if (checkInterval) checkInterval.value = '5';
- const checkThresh = document.getElementById('route-modal-check-threshold');
- if (checkThresh) checkThresh.value = '3';
- toggleRouteCheckModeUI();
- populateInterfaceSelect('route-modal-iface');
- // Populate tables
- tableSelect.innerHTML = '';
- (state.routingTables || [{ name: 'main' }]).forEach(t => {
- const opt = document.createElement('option');
- opt.value = t.name;
- opt.innerText = t.name;
- if (t.name === 'main') opt.selected = true;
- tableSelect.appendChild(opt);
- });
- document.getElementById('route-modal').classList.remove('hidden');
- }
- function openEditRouteModal(id) {
- const r = (state.routes || []).find(route => route.id === id);
- if (!r) return;
- const isStatic = !!r.static;
- document.getElementById('route-modal-title').innerText = isStatic
- ? `Edit Route: ${r.dst_address}`
- : `Route Properties (Read Only): ${r.dst_address}`;
- document.getElementById('route-modal-id').value = r.id;
- document.getElementById('route-modal-old-dst').value = r.dst_address || '';
- document.getElementById('route-modal-old-gw').value = r.gateway || '';
- document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
- document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
- document.getElementById('route-modal-old-iface').value = r.interface || '';
- const dstInput = document.getElementById('route-modal-dst');
- const gwInput = document.getElementById('route-modal-gw');
- const distInput = document.getElementById('route-modal-distance');
- const ifaceSelect = document.getElementById('route-modal-iface');
- const tableSelect = document.getElementById('route-modal-table');
- const commentInput = document.getElementById('route-modal-comment');
- const disCheck = document.getElementById('route-modal-disabled');
- const saveBtn = document.querySelector('#route-modal button[type="submit"]');
- dstInput.value = r.dst_address;
- gwInput.value = r.gateway || '';
- distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
- commentInput.value = r.comment || '';
- disCheck.checked = !!r.disabled;
- const checkGw = document.getElementById('route-modal-check-gw');
- if (checkGw) checkGw.value = r.check_gateway || 'none';
- const checkTarget = document.getElementById('route-modal-check-target');
- if (checkTarget) checkTarget.value = r.check_target || '1.1.1.1';
- const checkInterval = document.getElementById('route-modal-check-interval');
- if (checkInterval) checkInterval.value = r.check_interval || 5;
- const checkThresh = document.getElementById('route-modal-check-threshold');
- if (checkThresh) checkThresh.value = r.check_threshold || 3;
- toggleRouteCheckModeUI();
- dstInput.disabled = !isStatic;
- gwInput.disabled = !isStatic;
- distInput.disabled = !isStatic;
- ifaceSelect.disabled = !isStatic;
- tableSelect.disabled = !isStatic;
- commentInput.disabled = !isStatic;
- disCheck.disabled = !isStatic;
- if (checkGw) checkGw.disabled = !isStatic;
- if (checkTarget) checkTarget.disabled = !isStatic;
- if (checkInterval) checkInterval.disabled = !isStatic;
- if (checkThresh) checkThresh.disabled = !isStatic;
- if (saveBtn) {
- if (isStatic) {
- saveBtn.classList.remove('hidden');
- } else {
- saveBtn.classList.add('hidden');
- }
- }
- populateInterfaceSelect('route-modal-iface', r.interface);
- tableSelect.innerHTML = '';
- (state.routingTables || [{ name: 'main' }]).forEach(t => {
- const opt = document.createElement('option');
- opt.value = t.name;
- opt.innerText = t.name;
- if (t.name === (r.routing_table || 'main')) opt.selected = true;
- tableSelect.appendChild(opt);
- });
- document.getElementById('route-modal').classList.remove('hidden');
- }
- function closeRouteModal() {
- document.getElementById('route-modal').classList.add('hidden');
- }
- function setRouteCheckTarget(ip) {
- const inp = document.getElementById('route-modal-check-target');
- if (inp) inp.value = ip;
- }
- function toggleRouteCheckModeUI() {
- const mode = document.getElementById('route-modal-check-gw')?.value || 'none';
- const targetRow = document.getElementById('route-row-check-target');
- const paramsRow = document.getElementById('route-row-check-params');
- if (mode === 'none') {
- if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
- if (paramsRow) paramsRow.classList.add('opacity-40', 'pointer-events-none');
- } else if (mode === 'ping') {
- if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
- if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
- } else { // internet
- if (targetRow) targetRow.classList.remove('opacity-40', 'pointer-events-none');
- if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
- }
- }
- async function submitSaveRoute(e) {
- e.preventDefault();
- const id = document.getElementById('route-modal-id').value;
- const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
- const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
- const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
- const oldTable = document.getElementById('route-modal-old-table')?.value || '';
- const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
- const dst = document.getElementById('route-modal-dst').value.trim();
- const gw = document.getElementById('route-modal-gw').value.trim();
- const table = document.getElementById('route-modal-table').value;
- const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
- const iface = document.getElementById('route-modal-iface').value;
- const comment = document.getElementById('route-modal-comment').value.trim();
- const disabled = document.getElementById('route-modal-disabled').checked;
- const check_gateway = document.getElementById('route-modal-check-gw')?.value || 'none';
- const check_target = document.getElementById('route-modal-check-target')?.value.trim() || '1.1.1.1';
- const check_interval = parseInt(document.getElementById('route-modal-check-interval')?.value, 10) || 5;
- const check_threshold = parseInt(document.getElementById('route-modal-check-threshold')?.value, 10) || 3;
- if (!dst) {
- showToast('Error', 'Destination address is required', 'error');
- return;
- }
- if (!gw && !iface) {
- showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
- return;
- }
- const payload = {
- id,
- old_dst_address: oldDst,
- old_gateway: oldGw,
- old_routing_table: oldTable,
- old_interface: oldIface,
- dst_address: dst,
- gateway: gw || iface,
- routing_table: table,
- distance,
- interface: iface,
- comment,
- disabled,
- check_gateway,
- check_target,
- check_interval,
- check_threshold
- };
- if (oldDistStr !== undefined && oldDistStr !== '') {
- payload.old_distance = parseInt(oldDistStr, 10);
- }
- try {
- const res = await fetch(`${API_BASE}/routes`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(payload)
- });
- if (res.ok) {
- showToast('Route Saved', `Route to ${dst} installed`, 'success');
- closeRouteModal();
- loadRoutes();
- } else {
- const err = await res.json();
- showToast('Error', err.message || 'Failed to save route', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function toggleRouteState(id, disabled) {
- try {
- const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ disabled })
- });
- if (res.ok) loadRoutes();
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deleteRoute(id) {
- if (!confirm('Are you sure you want to delete this route?')) return;
- try {
- const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
- if (res.ok) {
- showToast('Deleted', 'Route removed', 'success');
- loadRoutes();
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // ----------------- Policy Rules (/ip route rule) -----------------
- function renderPolicyRules() {
- const tbody = document.getElementById('rules-table-body');
- const empty = document.getElementById('rules-empty');
- if (!tbody) return;
- const showSystem = document.getElementById('prule-show-system')?.checked;
- const filtered = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
- const countBadge = document.getElementById('rules-count-badge');
- if (countBadge) countBadge.innerText = `${filtered.length} Rules`;
- const bRules = document.getElementById('routes-badge-rules');
- if (bRules) bRules.innerText = filtered.length;
- if (filtered.length === 0) {
- empty?.classList.remove('hidden');
- tbody.innerHTML = '';
- return;
- }
- empty?.classList.add('hidden');
- const sig = `${showSystem}|` + filtered.map(pr => `${pr.id}:${pr.priority}:${pr.src_address}:${pr.dst_address}:${pr.table}:${pr.routing_mark}`).join(';');
- if (tbody.dataset.sig === sig) return;
- tbody.dataset.sig = sig;
- tbody.innerHTML = '';
- filtered.forEach(pr => {
- const isSys = pr.is_default || pr.is_system;
- const tr = document.createElement('tr');
- tr.className = `hover:bg-slate-800/40 transition text-xs ${isSys ? 'opacity-70 bg-slate-950/20' : ''}`;
- tr.innerHTML = `
- <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
- <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
- <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
- <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
- <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
- <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
- <td class="py-2.5 px-3 text-right font-sans">
- ${!pr.is_default ? `
- <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
- ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
- </td>
- `;
- tbody.appendChild(tr);
- });
- }
- function openAddPolicyRuleModal() {
- const userRules = (state.policyRules || []).filter(pr => !pr.is_default && !pr.is_system);
- document.getElementById('prule-modal-pref').value = userRules.length * 10 + 1000;
- document.getElementById('prule-modal-mark').value = '';
- document.getElementById('prule-modal-src').value = '';
- document.getElementById('prule-modal-dst').value = '';
- const sel = document.getElementById('prule-modal-table');
- sel.innerHTML = '';
- (state.routingTables || []).forEach(t => {
- const opt = document.createElement('option');
- opt.value = t.name;
- opt.innerText = t.name;
- sel.appendChild(opt);
- });
- document.getElementById('prule-modal').classList.remove('hidden');
- }
- function closePolicyRuleModal() {
- document.getElementById('prule-modal').classList.add('hidden');
- }
- async function submitSavePolicyRule(e) {
- e.preventDefault();
- const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
- const mark = document.getElementById('prule-modal-mark').value.trim();
- const src = document.getElementById('prule-modal-src').value.trim();
- const dst = document.getElementById('prule-modal-dst').value.trim();
- const table = document.getElementById('prule-modal-table').value;
- const action = document.getElementById('prule-modal-action').value;
- try {
- const res = await fetch(`${API_BASE}/routing/rules`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
- });
- if (res.ok) {
- showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
- closePolicyRuleModal();
- loadRoutes();
- } else {
- const err = await res.json();
- showToast('Error', err.message, 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deletePolicyRule(id) {
- if (!confirm('Are you sure you want to remove this policy rule?')) return;
- try {
- const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
- if (res.ok) {
- showToast('Rule Removed', 'Policy rule deleted', 'success');
- loadRoutes();
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // ----------------- Routing Tables -----------------
- function renderRoutingTables() {
- const tbody = document.getElementById('tables-table-body');
- if (!tbody) return;
- const tables = state.routingTables || [];
- const sig = tables.map(t => `${t.table_id}:${t.name}:${t.comment}`).join(';');
- if (tbody.dataset.sig === sig) return;
- tbody.dataset.sig = sig;
- tbody.innerHTML = '';
- (state.routingTables || []).forEach(t => {
- const tr = document.createElement('tr');
- tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
- tr.innerHTML = `
- <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
- <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
- <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
- `;
- tbody.appendChild(tr);
- });
- }
- function openAddTableModal() {
- document.getElementById('table-modal-name').value = '';
- document.getElementById('table-modal-id').value = '';
- document.getElementById('table-modal-comment').value = '';
- document.getElementById('table-modal').classList.remove('hidden');
- }
- function closeTableModal() {
- document.getElementById('table-modal').classList.add('hidden');
- }
- async function submitSaveTable(e) {
- e.preventDefault();
- const name = document.getElementById('table-modal-name').value.trim();
- const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
- const comment = document.getElementById('table-modal-comment').value.trim();
- try {
- const res = await fetch(`${API_BASE}/routing/tables`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ name, table_id: id, comment })
- });
- if (res.ok) {
- showToast('Table Created', `Routing table ${name} registered`, 'success');
- closeTableModal();
- loadRoutes();
- } else {
- const err = await res.json();
- showToast('Error', err.message, 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function loadDebianConfig() {
- const view = document.getElementById('debian-config-view');
- view.innerText = 'Generating live configuration...';
- try {
- const res = await fetch(`${API_BASE}/debian/config`);
- const data = await res.json();
- view.innerText = data.content || '# Empty config';
- } catch (err) {
- view.innerText = 'Failed to generate Debian network config.';
- }
- }
- async function saveDebianConfig() {
- try {
- const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
- const data = await res.json();
- if (res.ok) {
- showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
- loadDebianConfig();
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- function showToast(title, message, type = 'info') {
- const container = document.getElementById('toast-container');
- const toast = document.createElement('div');
- const borderColors = {
- success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
- error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
- info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
- };
- 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}`;
- toast.innerHTML = `
- <div class="flex-1">
- <div class="font-bold text-xs text-white">${escapeHtml(title)}</div>
- <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${escapeHtml(message)}</div>
- </div>
- `;
- container.appendChild(toast);
- requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
- setTimeout(() => {
- toast.classList.add('opacity-0', 'translate-y-2');
- setTimeout(() => toast.remove(), 300);
- }, 4000);
- }
- function formatTraffic(bytesPerSec) {
- if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
- const kb = bytesPerSec / 1024;
- if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
- const mb = kb / 1024;
- return `${mb.toFixed(2)} MB/s`;
- }
- function toggleSidebar() {
- const sb = document.getElementById('sidebar');
- sb.classList.toggle('-translate-x-full');
- }
- // ======================== EoIP (Ethernet over IP) ========================
- async function loadEoIP(populate = true) {
- try {
- const res = await fetch(`${API_BASE}/vpn/eoip`);
- const data = await res.json();
- state.eoipTunnels = Array.isArray(data) ? data : [];
- const badge = document.getElementById('eoip-count-badge');
- if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
- const sideBadge = document.getElementById('badge-eoip-count');
- if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
- renderEoIPTunnels();
- } catch (err) {
- console.error('Failed to load EoIP:', err);
- }
- }
- function renderEoIPTunnels() {
- const tbody = document.getElementById('eoip-table-body');
- const empty = document.getElementById('eoip-empty');
- if (!tbody) return;
- tbody.innerHTML = '';
- const tunnels = state.eoipTunnels || [];
- if (tunnels.length === 0) {
- empty?.classList.remove('hidden');
- return;
- }
- empty?.classList.add('hidden');
- tunnels.forEach(t => {
- const tr = document.createElement('tr');
- tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
- tr.innerHTML = `
- <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
- <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
- <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
- <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>
- <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
- <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
- <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
- <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
- <td class="py-2.5 px-3 font-mono text-[11px]">
- <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
- <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
- </td>
- <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
- <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
- <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>
- <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
- <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
- </td>
- `;
- tbody.appendChild(tr);
- });
- }
- function openAddEoIPModal() {
- document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
- document.getElementById('eoip-modal-id').value = '';
- document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
- document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
- document.getElementById('eoip-modal-remote').value = '';
- document.getElementById('eoip-modal-ip').value = '';
- document.getElementById('eoip-modal-local').value = '';
- document.getElementById('eoip-modal-mac').value = '';
- document.getElementById('eoip-modal-mtu').value = '1500';
- document.getElementById('eoip-modal-comment').value = '';
- document.getElementById('eoip-modal-clampmss').checked = true;
- document.getElementById('eoip-modal-disabled').checked = false;
- document.getElementById('eoip-modal').classList.remove('hidden');
- }
- function openEditEoIPModal(id) {
- const t = (state.eoipTunnels || []).find(tun => tun.id === id);
- if (!t) return;
- document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
- document.getElementById('eoip-modal-id').value = t.id;
- document.getElementById('eoip-modal-name').value = t.name;
- document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
- document.getElementById('eoip-modal-remote').value = t.remote_address;
- document.getElementById('eoip-modal-ip').value = t.ip_address || '';
- document.getElementById('eoip-modal-local').value = t.local_address || '';
- document.getElementById('eoip-modal-mac').value = t.mac_address || '';
- document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
- document.getElementById('eoip-modal-comment').value = t.comment || '';
- document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
- document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
- document.getElementById('eoip-modal').classList.remove('hidden');
- }
- function closeEoIPModal() {
- document.getElementById('eoip-modal').classList.add('hidden');
- }
- async function submitSaveEoIP(e) {
- e.preventDefault();
- const id = document.getElementById('eoip-modal-id').value;
- const name = document.getElementById('eoip-modal-name').value.trim();
- const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
- const remote = document.getElementById('eoip-modal-remote').value.trim();
- const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
- const local = document.getElementById('eoip-modal-local').value.trim();
- const mac = document.getElementById('eoip-modal-mac').value.trim();
- const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
- const comment = document.getElementById('eoip-modal-comment').value.trim();
- const clampMss = document.getElementById('eoip-modal-clampmss').checked;
- const disabled = document.getElementById('eoip-modal-disabled').checked;
- try {
- const res = await fetch(`${API_BASE}/vpn/eoip`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- id,
- name,
- tunnel_id: tunnelId,
- remote_address: remote,
- ip_address: ipAddress,
- local_address: local,
- mac_address: mac,
- mtu,
- clamp_mss: clampMss,
- comment,
- disabled
- })
- });
- if (res.ok) {
- showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
- closeEoIPModal();
- loadEoIP(false);
- fetchData(false);
- } else {
- const err = await res.json();
- showToast('Error', err.message, 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function toggleEoIPState(id, disabled) {
- try {
- const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ disabled })
- });
- if (res.ok) {
- showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
- loadEoIP(false);
- fetchData(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deleteEoIP(id) {
- if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
- try {
- const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
- if (res.ok) {
- showToast('Deleted', 'EoIP tunnel removed', 'success');
- loadEoIP(false);
- fetchData(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // ======================== VXLAN (Virtual Extensible LAN) ========================
- async function loadVXLAN(populate = true) {
- try {
- const [tunnelsRes, vtepsRes] = await Promise.all([
- fetch(`${API_BASE}/vpn/vxlan`),
- fetch(`${API_BASE}/vpn/vxlan/vteps`)
- ]);
- if (tunnelsRes.ok) {
- state.vxlanTunnels = await tunnelsRes.json() || [];
- }
- if (vtepsRes.ok) {
- state.vxlanVteps = await vtepsRes.json() || [];
- }
- renderVXLANTable();
- renderVXLANVtepsTable();
- const countBadge = document.getElementById('vxlan-count-badge');
- if (countBadge) countBadge.innerText = `${(state.vxlanTunnels || []).length} Tunnels`;
- const vtepsCountBadge = document.getElementById('vxlan-vteps-count-badge');
- if (vtepsCountBadge) vtepsCountBadge.innerText = `${(state.vxlanVteps || []).length} VTEPs`;
- const navBadge = document.getElementById('badge-vxlan-count');
- if (navBadge) navBadge.innerText = (state.vxlanTunnels || []).length;
- } catch (err) {
- console.error('Error loading VXLAN:', err);
- }
- }
- function renderVXLANTable() {
- const tbody = document.getElementById('vxlan-table-body');
- const empty = document.getElementById('vxlan-empty');
- if (!tbody || !empty) return;
- tbody.innerHTML = '';
- const tunnels = state.vxlanTunnels || [];
- if (tunnels.length === 0) {
- empty.classList.remove('hidden');
- return;
- }
- empty.classList.add('hidden');
- tunnels.forEach(t => {
- const tr = document.createElement('tr');
- tr.className = 'hover:bg-slate-800/40 transition border-b border-slate-800/60';
- let flag = '';
- if (t.disabled) {
- flag = '<span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-400 font-bold border border-slate-700" title="Disabled">X</span>';
- } else if (t.running) {
- flag = '<span class="px-1.5 py-0.5 rounded text-[10px] bg-amber-950 text-amber-300 font-bold border border-amber-800/50" title="Running">R</span>';
- } else {
- flag = '<span class="px-1.5 py-0.5 rounded text-[10px] bg-rose-950 text-rose-300 font-bold border border-rose-800/50" title="Down">!</span>';
- }
- const vtepCount = (t.vteps || []).length;
- const underlayDesc = t.parent_interface || t.local_address ? `${t.parent_interface || '-'}${t.local_address ? ' / ' + t.local_address : ''}` : '(any)';
- tr.innerHTML = `
- <td class="py-2.5 px-3 text-center">${flag}</td>
- <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(t.name)}</td>
- <td class="py-2.5 px-3 font-bold text-amber-400 font-mono">${t.vni}</td>
- <td class="py-2.5 px-3 text-slate-300 font-mono">${t.port || 4789}</td>
- <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${escapeHtml(t.ip_address || '') || '<span class="text-slate-500 font-normal">Unassigned</span>'}</td>
- <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${escapeHtml(underlayDesc)}</td>
- <td class="py-2.5 px-3 text-slate-400 font-mono text-[11px]">${escapeHtml(t.mac_address || '-')}</td>
- <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
- <td class="py-2.5 px-3 font-mono">
- <span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-amber-300 border border-slate-700 cursor-pointer" onclick="openAddVXLANVtepModal('${escapeHtml(t.name)}')" title="Click to add VTEP peer">${vtepCount} VTEP${vtepCount === 1 ? '' : 's'}</span>
- </td>
- <td class="py-2.5 px-3 font-mono text-[11px]">
- <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
- <span class="text-amber-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
- </td>
- <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(t.comment || '')}">${escapeHtml(t.comment || '-')}</td>
- <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
- <button onclick="toggleVXLANState('${t.id}', ${!t.disabled})" class="text-xs ${t.disabled ? 'text-amber-400' : 'text-slate-400'} hover:underline">${t.disabled ? 'Enable' : 'Disable'}</button>
- <button onclick="openEditVXLANModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
- <button onclick="deleteVXLAN('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
- </td>
- `;
- tbody.appendChild(tr);
- });
- }
- function renderVXLANVtepsTable() {
- const tbody = document.getElementById('vxlan-vteps-table-body');
- const empty = document.getElementById('vxlan-vteps-empty');
- if (!tbody || !empty) return;
- tbody.innerHTML = '';
- const vteps = state.vxlanVteps || [];
- if (vteps.length === 0) {
- empty.classList.remove('hidden');
- return;
- }
- empty.classList.add('hidden');
- vteps.forEach(v => {
- const tr = document.createElement('tr');
- tr.className = 'hover:bg-slate-800/40 transition border-b border-slate-800/60';
- tr.innerHTML = `
- <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(v.interface)}</td>
- <td class="py-2.5 px-3 text-amber-400 font-mono font-semibold">${escapeHtml(v.remote_ip)}</td>
- <td class="py-2.5 px-3 text-slate-300 font-mono">${v.port > 0 ? v.port : 'default'}</td>
- <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]" title="${escapeHtml(v.comment || '')}">${escapeHtml(v.comment || '-')}</td>
- <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
- <button onclick="deleteVXLANVtep('${escapeHtml(v.interface)}', '${escapeHtml(v.id || v.remote_ip)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
- </td>
- `;
- tbody.appendChild(tr);
- });
- }
- function openAddVXLANModal() {
- document.getElementById('vxlan-modal-title').innerText = 'Add VXLAN Interface';
- document.getElementById('vxlan-modal-id').value = '';
- document.getElementById('vxlan-modal-name').value = `vxlan${(state.vxlanTunnels || []).length + 100}`;
- document.getElementById('vxlan-modal-vni').value = (state.vxlanTunnels || []).length + 100;
- document.getElementById('vxlan-modal-port').value = '4789';
- document.getElementById('vxlan-modal-ip').value = '';
- document.getElementById('vxlan-modal-parent').value = '';
- document.getElementById('vxlan-modal-local').value = '';
- document.getElementById('vxlan-modal-remote').value = '';
- document.getElementById('vxlan-modal-group').value = '';
- document.getElementById('vxlan-modal-mac').value = '';
- document.getElementById('vxlan-modal-mtu').value = '1500';
- document.getElementById('vxlan-modal-comment').value = '';
- document.getElementById('vxlan-modal-learning').checked = true;
- document.getElementById('vxlan-modal-disabled').checked = false;
- document.getElementById('vxlan-modal').classList.remove('hidden');
- }
- function openEditVXLANModal(id) {
- const t = (state.vxlanTunnels || []).find(tun => tun.id === id);
- if (!t) return;
- document.getElementById('vxlan-modal-title').innerText = `Edit VXLAN Interface (${t.name})`;
- document.getElementById('vxlan-modal-id').value = t.id;
- document.getElementById('vxlan-modal-name').value = t.name;
- document.getElementById('vxlan-modal-vni').value = t.vni;
- document.getElementById('vxlan-modal-port').value = t.port || 4789;
- document.getElementById('vxlan-modal-ip').value = t.ip_address || '';
- document.getElementById('vxlan-modal-parent').value = t.parent_interface || '';
- document.getElementById('vxlan-modal-local').value = t.local_address || '';
- document.getElementById('vxlan-modal-remote').value = t.remote_address || '';
- document.getElementById('vxlan-modal-group').value = t.group || '';
- document.getElementById('vxlan-modal-mac').value = t.mac_address || '';
- document.getElementById('vxlan-modal-mtu').value = t.mtu || 1500;
- document.getElementById('vxlan-modal-comment').value = t.comment || '';
- document.getElementById('vxlan-modal-learning').checked = t.learning !== false;
- document.getElementById('vxlan-modal-disabled').checked = !!t.disabled;
- document.getElementById('vxlan-modal').classList.remove('hidden');
- }
- function closeVXLANModal() {
- document.getElementById('vxlan-modal').classList.add('hidden');
- }
- async function submitSaveVXLAN(e) {
- e.preventDefault();
- const id = document.getElementById('vxlan-modal-id').value;
- const name = document.getElementById('vxlan-modal-name').value.trim();
- const vni = parseInt(document.getElementById('vxlan-modal-vni').value);
- const port = parseInt(document.getElementById('vxlan-modal-port').value) || 4789;
- const ipAddress = document.getElementById('vxlan-modal-ip').value.trim();
- const parentInterface = document.getElementById('vxlan-modal-parent').value.trim();
- const local = document.getElementById('vxlan-modal-local').value.trim();
- const remote = document.getElementById('vxlan-modal-remote').value.trim();
- const group = document.getElementById('vxlan-modal-group').value.trim();
- const mac = document.getElementById('vxlan-modal-mac').value.trim();
- const mtu = parseInt(document.getElementById('vxlan-modal-mtu').value) || 1500;
- const comment = document.getElementById('vxlan-modal-comment').value.trim();
- const learning = document.getElementById('vxlan-modal-learning').checked;
- const disabled = document.getElementById('vxlan-modal-disabled').checked;
- try {
- const res = await fetch(`${API_BASE}/vpn/vxlan`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- id,
- name,
- vni,
- port,
- ip_address: ipAddress,
- parent_interface: parentInterface,
- local_address: local,
- remote_address: remote,
- group,
- mac_address: mac,
- mtu,
- learning,
- comment,
- disabled
- })
- });
- if (res.ok) {
- showToast('VXLAN Saved', `Interface ${name} configured successfully`, 'success');
- closeVXLANModal();
- loadVXLAN(false);
- fetchData(false);
- } else {
- const err = await res.json();
- showToast('Error', err.message, 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function toggleVXLANState(id, disabled) {
- try {
- const res = await fetch(`${API_BASE}/vpn/vxlan/${encodeURIComponent(id)}/state`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ disabled })
- });
- if (res.ok) {
- showToast(disabled ? 'Disabled' : 'Enabled', 'VXLAN interface state updated', 'info');
- loadVXLAN(false);
- fetchData(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deleteVXLAN(id) {
- if (!confirm('Are you sure you want to delete this VXLAN interface?')) return;
- try {
- const res = await fetch(`${API_BASE}/vpn/vxlan/${encodeURIComponent(id)}`, { method: 'DELETE' });
- if (res.ok) {
- showToast('Deleted', 'VXLAN interface removed', 'success');
- loadVXLAN(false);
- fetchData(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- function openAddVXLANVtepModal(defaultIface = '') {
- const sel = document.getElementById('vxlan-vtep-modal-interface');
- if (sel) {
- sel.innerHTML = '';
- const tunnels = state.vxlanTunnels || [];
- tunnels.forEach(t => {
- const opt = document.createElement('option');
- opt.value = t.name;
- opt.innerText = `${t.name} (VNI ${t.vni})`;
- if (defaultIface && t.name === defaultIface) {
- opt.selected = true;
- }
- sel.appendChild(opt);
- });
- }
- document.getElementById('vxlan-vtep-modal-remote').value = '';
- document.getElementById('vxlan-vtep-modal-port').value = '';
- document.getElementById('vxlan-vtep-modal-comment').value = '';
- document.getElementById('vxlan-vtep-modal').classList.remove('hidden');
- }
- function closeVXLANVtepModal() {
- document.getElementById('vxlan-vtep-modal').classList.add('hidden');
- }
- async function submitSaveVXLANVtep(e) {
- e.preventDefault();
- const iface = document.getElementById('vxlan-vtep-modal-interface').value;
- const remote = document.getElementById('vxlan-vtep-modal-remote').value.trim();
- const port = parseInt(document.getElementById('vxlan-vtep-modal-port').value) || 0;
- const comment = document.getElementById('vxlan-vtep-modal-comment').value.trim();
- try {
- const res = await fetch(`${API_BASE}/vpn/vxlan/vteps`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- interface: iface,
- remote_ip: remote,
- port,
- comment
- })
- });
- if (res.ok) {
- showToast('VTEP Added', `Peer ${remote} added to ${iface}`, 'success');
- closeVXLANVtepModal();
- loadVXLAN(false);
- fetchData(false);
- } else {
- const err = await res.json();
- showToast('Error', err.message, 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deleteVXLANVtep(iface, vtepIdOrIp) {
- if (!confirm(`Are you sure you want to remove VTEP ${vtepIdOrIp} from ${iface}?`)) return;
- try {
- const res = await fetch(`${API_BASE}/vpn/vxlan/${encodeURIComponent(iface)}/vteps/${encodeURIComponent(vtepIdOrIp)}`, {
- method: 'DELETE'
- });
- if (res.ok) {
- showToast('Deleted', 'Remote VTEP removed', 'success');
- loadVXLAN(false);
- fetchData(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // ======================== AeroTUN (Custom Encrypted VPN with Adaptive LZ4) ========================
- const aeroRateSamples = new Map();
- const aeroLiveRates = new Map();
- async function loadAeroTUN(populate = true) {
- try {
- const [tunnelsRes, statsRes] = await Promise.all([
- fetch(`${API_BASE}/vpn/aerotun/tunnels`),
- fetch(`${API_BASE}/vpn/aerotun/stats`)
- ]);
- if (tunnelsRes.ok) {
- const data = await tunnelsRes.json();
- state.aerotunTunnels = Array.isArray(data) ? data : [];
- const now = Date.now();
- for (const t of state.aerotunTunnels) {
- const old = aeroRateSamples.get(t.id), seconds = old ? (now-old.time)/1000 : 0;
- if (seconds >= 0.5 && seconds <= 60 && t.rx_bytes >= old.rx && t.tx_bytes >= old.tx && t.packets_rx >= old.prx && t.packets_tx >= old.ptx) {
- aeroLiveRates.set(t.id,{rx:(t.rx_bytes-old.rx)*8/seconds/1e6,tx:(t.tx_bytes-old.tx)*8/seconds/1e6,prx:(t.packets_rx-old.prx)/seconds,ptx:(t.packets_tx-old.ptx)/seconds});
- } else if (!old || seconds > 60 || t.rx_bytes < old.rx || t.tx_bytes < old.tx) aeroLiveRates.delete(t.id);
- if (!old || seconds >= 0.5) aeroRateSamples.set(t.id,{time:now,rx:t.rx_bytes||0,tx:t.tx_bytes||0,prx:t.packets_rx||0,ptx:t.packets_tx||0});
- }
- }
- if (statsRes.ok) {
- state.aerotunStats = await statsRes.json();
- }
- const countBadge = document.getElementById('aerotun-count-badge');
- if (countBadge) countBadge.innerText = `${(state.aerotunTunnels || []).length} Tunnels`;
- const sideBadge = document.getElementById('badge-aerotun-count');
- if (sideBadge) sideBadge.innerText = (state.aerotunTunnels || []).length;
- renderAeroTUN();
- if (state.aeroHealthSelected) await refreshAeroTUNHealth();
- } catch (err) {
- console.error('Failed to load AeroTUN:', err);
- }
- }
- function renderAeroTUN() {
- const tbody = document.getElementById('aerotun-table-body');
- const empty = document.getElementById('aerotun-empty');
- // Update summary cards
- const stats = state.aerotunStats || {};
- const tunnels = state.aerotunTunnels || [];
- const statActive = document.getElementById('aerotun-stat-active');
- if (statActive) {
- const activeCount = tunnels.filter(t => t.connected).length;
- statActive.innerText = `${activeCount} / ${tunnels.length}`;
- }
- const statSaved = document.getElementById('aerotun-stat-saved');
- if (statSaved) {
- statSaved.innerText = formatBytes(stats.total_saved_bytes || 0);
- }
- const statRatio = document.getElementById('aerotun-stat-ratio');
- if (statRatio) {
- statRatio.innerText = stats.average_ratio || '1.00x (0% saved)';
- }
- const statTraffic = document.getElementById('aerotun-stat-traffic');
- if (statTraffic) {
- statTraffic.innerText = `↓ ${formatBytes(stats.total_rx_bytes || 0)} / ↑ ${formatBytes(stats.total_tx_bytes || 0)}`;
- }
- if (!tbody) return;
- tbody.innerHTML = '';
- if (tunnels.length === 0) {
- empty?.classList.remove('hidden');
- return;
- }
- empty?.classList.add('hidden');
- tunnels.forEach(t => {
- const tr = document.createElement('tr');
- tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
- const modeBadge = t.mode === 'server'
- ? `<span class="px-2 py-0.5 rounded text-[10px] font-mono bg-sky-500/20 text-sky-300 border border-sky-500/30 font-semibold uppercase">Server</span>`
- : `<span class="px-2 py-0.5 rounded text-[10px] font-mono bg-indigo-500/20 text-indigo-300 border border-indigo-500/30 font-semibold uppercase">Client</span>`;
- const endpointInfo = t.mode === 'server'
- ? `<span class="text-sky-300 font-mono">Port :${t.listen_port || 51830}</span>`
- : `<span class="text-indigo-300 font-mono">${escapeHtml(t.remote_endpoint || '(not set)')}</span>`;
- const compBadge = t.compression
- ? `<span class="px-1.5 py-0.5 rounded text-[10px] font-mono bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 font-semibold" title="Adaptive LZ4 active">${t.compression_ratio || 'LZ4'}</span>`
- : `<span class="text-slate-500 text-[10px]">Off</span>`;
- const activePeer = t.connected && t.active_peer_endpoint
- ? `<span class="text-emerald-400 font-mono text-[11px]" title="Last authenticated packet: ${escapeHtml(t.last_handshake || 'just now')}; dropped: ${t.dropped_packets || 0}; auth failures: ${t.auth_failures || 0}; replay drops: ${t.replay_drops || 0}${t.last_error ? '; last error: ' + escapeHtml(t.last_error) : ''}">● ${escapeHtml(t.active_peer_endpoint)}</span>`
- : `<span class="text-slate-500 text-[11px]">${t.last_error ? 'Failed: ' + escapeHtml(t.last_error) : (!t.running ? (t.disabled ? 'Saved / disabled' : 'Stopped') : (t.mode === 'server' ? 'Waiting for peer...' : 'Connecting...'))}</span>`;
- const rawRx = formatBytes(t.rx_bytes || 0);
- const rawTx = formatBytes(t.tx_bytes || 0);
- const wireRx = formatBytes(t.wire_bytes_in || 0);
- const wireTx = formatBytes(t.wire_bytes_out || 0);
- const rate = aeroLiveRates.get(t.id);
- const id = encodeURIComponent(String(t.id || '')).replace(/'/g, '%27');
- tr.innerHTML = `
- <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.connected, t.disabled)}</td>
- <td class="py-2.5 px-3 font-bold text-white font-mono flex items-center gap-1.5">
- <span>${escapeHtml(t.name)}</span>
- ${t.default_route ? '<span class="text-[9px] px-1 rounded bg-amber-500/20 text-amber-300 border border-amber-500/30">DEF</span>' : ''}
- <span class="text-slate-400 text-[10px]">v${t.protocol_version || 2}</span>
- </td>
- <td class="py-2.5 px-3">${modeBadge}</td>
- <td class="py-2.5 px-3 text-xs font-mono">${endpointInfo}</td>
- <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${escapeHtml(t.local_address || '-')}</td>
- <td class="py-2.5 px-3">${compBadge}</td>
- <td class="py-2.5 px-3">${activePeer}</td>
- <td class="py-2.5 px-3 font-mono text-[11px]">
- <span class="text-emerald-400">↓ ${rawRx}</span>
- <span class="text-cyan-400 ml-1">↑ ${rawTx}</span>
- ${rate ? `<div class="text-slate-400">↓ ${rate.rx.toFixed(2)} / ↑ ${rate.tx.toFixed(2)} Mbit/s</div>` : ''}
- </td>
- <td class="py-2.5 px-3 font-mono text-[11px]">
- <span class="text-slate-400">↓ ${wireRx}</span>
- <span class="text-slate-400 ml-1">↑ ${wireTx}</span>
- </td>
- <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(t.comment || '')}">${escapeHtml(t.comment || '-')}</td>
- <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
- <button onclick="openAeroTUNHealth('${id}')" class="text-xs text-sky-400 hover:text-sky-300 font-medium">Health</button>
- ${t.running
- ? `<button onclick="stopAeroTUNTunnel('${t.id}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Stop</button>`
- : `<button onclick="startAeroTUNTunnel('${t.id}')" class="text-xs text-emerald-400 hover:text-emerald-300 font-medium">Start</button>`
- }
- <button onclick="toggleAeroTUNState('${t.id}', ${!t.disabled})" class="text-xs ${t.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${t.disabled ? 'Enable' : 'Disable'}</button>
- <button onclick="openEditAeroTUNModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
- <button onclick="deleteAeroTUN('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
- </td>
- `;
- tbody.appendChild(tr);
- });
- }
- async function openAeroTUNHealth(encodedID) {
- state.aeroHealthSelected = decodeURIComponent(encodedID);
- const tunnel=(state.aerotunTunnels||[]).find(x=>x.id===state.aeroHealthSelected);
- let underlay='';try {underlay=new URL(`http://${tunnel?.remote_endpoint||tunnel?.active_peer_endpoint||''}`).hostname.replace(/^\[|\]$/g,'')} catch {}
- document.getElementById('aerotun-compare-host').value=underlay;
- document.getElementById('aerotun-compare-result').textContent='';
- document.getElementById('aerotun-health-result').textContent = '';
- document.getElementById('aerotun-health-panel').classList.remove('hidden');
- await refreshAeroTUNHealth();
- document.getElementById('aerotun-health-panel').scrollIntoView({behavior:'smooth',block:'nearest'});
- }
- function closeAeroTUNHealth() { aeroCompareCancel=true; state.aeroHealthSelected = ''; document.getElementById('aerotun-health-panel').classList.add('hidden'); }
- async function refreshAeroTUNHealth() {
- const id=state.aeroHealthSelected,t=(state.aerotunTunnels||[]).find(x=>x.id===id);if(!id)return;
- if(!t){document.getElementById('aerotun-health-status').textContent='Tunnel no longer exists.';return}
- document.getElementById('aerotun-health-title').textContent=`Health: ${t.name}`;
- try {
- const response=await fetch(`${API_BASE}/vpn/aerotun/health`);if(!response.ok)throw new Error(await responseError(response));const data=await response.json();if(state.aeroHealthSelected!==id)return;
- const current=(data.states||[]).find(x=>x.tunnel_id===id);const status=current?.status||'unknown';const since=current?.since&&!current.since.startsWith('0001')?new Date(current.since).toLocaleString():'—';const rate=aeroLiveRates.get(id);
- const d=t.drop_breakdown;
- document.getElementById('aerotun-health-status').textContent=`Status: ${status} since ${since} · Backend: ${t.backend||'—'} · MTU: ${t.mtu||'—'} / configured ${t.configured_mtu||(!t.running?t.mtu:'—')||'—'} · Last authenticated packet: ${t.last_handshake||'never'} · Drops: ${t.dropped_packets||0}${d?` (outgoing invalid ${d.invalid_outgoing}, session ${d.missing_session}, send ${d.send_failure}, incoming invalid ${d.invalid_incoming}, source policy ${d.source_policy}, interface ${d.interface_write})`:''} · Authentication failures: ${t.auth_failures||0} · Replay drops: ${t.replay_drops||0}${Number.isFinite(data.service_cpu_percent)?` · Service CPU (all features): ${data.service_cpu_percent.toFixed(1)}% of one core`:''}${rate?` · RX/TX: ${rate.rx.toFixed(2)} / ${rate.tx.toFixed(2)} Mbit/s, ${rate.prx.toFixed(0)} / ${rate.ptx.toFixed(0)} packets/s`:''}${t.last_error?` · Last error: ${t.last_error}`:''}`;
- const events=(data.events||[]).filter(e=>e.tunnel_id===id).slice(0,100),node=document.getElementById('aerotun-health-history');node.replaceChildren();
- if(!events.length){node.textContent='No events recorded yet.';return}
- for(const e of events){const line=document.createElement('div');line.textContent=`${new Date(e.time).toLocaleString()} · ${e.type==='check'?'Check':(e.previous?`${e.previous} → ${e.status}${e.previous_duration_seconds?` (after ${Math.round(e.previous_duration_seconds)} s)`:''}`:e.status)}${e.detail?` · ${e.detail}`:''}`;node.appendChild(line)}
- } catch(e){document.getElementById('aerotun-health-history').textContent=`Health history unavailable: ${e.message}`}
- }
- async function runAeroTUNHealthCheck() {
- const id=state.aeroHealthSelected;if(!id)return;const button=document.getElementById('aerotun-health-check-btn'),output=document.getElementById('aerotun-health-result');button.disabled=true;output.textContent='Checking…';
- try {const response=await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/health-check`,{method:'POST'});if(!response.ok)throw new Error(await responseError(response));const r=await response.json();if(state.aeroHealthSelected!==id)return;output.textContent=`Peer echo: ${r.reachability}${r.rtt_ms!=null?` · RTT ${r.rtt_upper_bound?'<':''}${r.rtt_ms} ms`:''} · ${r.mtu}-byte overlay probe: ${r.mtu_probe}. ${r.explanation}`;await refreshAeroTUNHealth()}
- catch(e){if(state.aeroHealthSelected===id)output.textContent=`Health check failed: ${e.message}`}
- finally {button.disabled=false}
- }
- let aeroCompareRunning=false, aeroCompareCancel=false;
- function stopAeroTUNComparison() { aeroCompareCancel=true;document.getElementById('aerotun-compare-result').textContent+='\nStopping after the current test.'; }
- async function runAeroTUNComparison() {
- if(aeroCompareRunning)return;
- const id=state.aeroHealthSelected,t=(state.aerotunTunnels||[]).find(x=>x.id===id),direct=document.getElementById('aerotun-compare-host').value.trim(),port=Number(document.getElementById('aerotun-compare-port').value),peer=(t?.peer_address||'').split('/')[0].trim();
- const output=document.getElementById('aerotun-compare-result'),button=document.getElementById('aerotun-compare-btn'),stop=document.getElementById('aerotun-compare-stop');
- if(!t?.connected||!peer||!direct||!Number.isInteger(port)||port<1||port>65535||peer===direct){output.textContent='A connected tunnel, peer IP, different direct server address and valid port are required.';return}
- if(peer.includes(':')||direct.includes(':')){output.textContent='This comparison currently supports IPv4 addresses or IPv4-resolvable hostnames.';return}
- aeroCompareRunning=true;aeroCompareCancel=false;button.disabled=true;stop.classList.remove('hidden');output.textContent='Starting. The direct address uses the system routing table.';
- const get=async(path,body)=>{const r=await fetch(`${API_BASE}${path}`,body?{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)}:{});if(!r.ok)throw new Error(await responseError(r));return r.json()};
- const results=[];
- try {
- for(const [path,target,direction] of [['Tunnel',peer,'tx'],['Tunnel',peer,'rx'],['Direct',direct,'tx'],['Direct',direct,'rx']]) {
- if(aeroCompareCancel)break;
- if((await get('/tools/bwtest/status')).running)throw new Error('Another bandwidth test is running; comparison stopped.');
- output.textContent+=`\n${path} ${direction.toUpperCase()}: testing…`;
- const started=await get('/tools/bwtest/start',{target,port,protocol:'tcp',direction,bandwidth_limit:0,packet_size:1200,streams:2,duration:8}),session=started.session_id;let status,complete=false;
- for(let i=0;i<30;i++){await new Promise(resolve=>setTimeout(resolve,1000));status=await get('/tools/bwtest/status');if(status.session_id!==session)throw new Error('Bandwidth test session changed; comparison stopped.');if(!status.running){complete=true;break}}
- if(!complete)throw new Error('Timed out waiting for the bandwidth test.');if(status.error)throw new Error(`${path} ${direction.toUpperCase()}: ${status.error}`);
- const value=status.summary?.[direction==='tx'?'avg_tx_mbps':'avg_rx_mbps'];if(!Number.isFinite(value)||value<=0)throw new Error(`${path} ${direction.toUpperCase()}: no delivered data.`);
- results.push(`${path} ${direction.toUpperCase()}: ${value.toFixed(2)} Mbit/s`);output.textContent='Results:\n'+results.join('\n');
- }
- if(aeroCompareCancel)output.textContent+='\nComparison stopped.';
- else output.textContent+='\nDirect results are meaningful only if both addresses reach the same server over different routes.';
- } catch(e){output.textContent+=`\nComparison incomplete: ${e.message}`}
- finally {aeroCompareRunning=false;button.disabled=false;stop.classList.add('hidden')}
- }
- let aeroModalGeneration = 0;
- let aeroIdentityDraft = '';
- let aeroSaving = false;
- let aeroPSKRequest = 0;
- function discardAeroIdentityDraft(id) {
- if (id) fetch(`${API_BASE}/vpn/aerotun/identity-drafts/${encodeURIComponent(id)}`, {method:'DELETE'}).catch(() => {});
- }
- async function generateAeroTUNIdentity() {
- const generation = aeroModalGeneration;
- const retry = document.getElementById('aerotun-retry-identity');
- if (aeroIdentityDraft) { discardAeroIdentityDraft(aeroIdentityDraft); aeroIdentityDraft = ''; }
- retry.classList.add('hidden');
- document.getElementById('aerotun-modal-public').value = '';
- try {
- const res = await fetch(`${API_BASE}/vpn/aerotun/identity-drafts`, {method:'POST'});
- if (!res.ok) throw new Error(await responseError(res));
- const draft = await res.json();
- if (generation !== aeroModalGeneration) { discardAeroIdentityDraft(draft.draft_id); return; }
- aeroIdentityDraft = draft.draft_id;
- document.getElementById('aerotun-modal-public').value = draft.public_key;
- updateAeroTUNSetupHint();
- } catch (err) {
- if (generation !== aeroModalGeneration) return;
- retry.classList.remove('hidden');
- updateAeroTUNSetupHint();
- showToast('Identity Generation Failed', err.message, 'error');
- }
- }
- function onAeroTUNModeChange() {
- const mode = document.getElementById('aerotun-modal-mode').value;
- const endpointInput = document.getElementById('aerotun-modal-endpoint');
- const portInput = document.getElementById('aerotun-modal-port');
- if (mode === 'server') {
- if (!portInput.value) portInput.value = '51830';
- endpointInput.placeholder = 'Optional / learned roaming peer';
- } else {
- endpointInput.placeholder = 'vpn.example.com:51830 (required)';
- if (!portInput.value) portInput.value = '';
- }
- }
- function onAeroTUNPeerChange() {
- const peer = document.getElementById('aerotun-modal-peer');
- const allowed = document.getElementById('aerotun-modal-allowed');
- const previous = peer.dataset.allowedDefault || '';
- const host = peer.value.trim().split('/')[0];
- const next = host ? `${host}/${host.includes(':') ? 128 : 32}` : '';
- if (allowed.value.trim() === previous) allowed.value = next;
- peer.dataset.allowedDefault = next;
- }
- async function generateAeroTUNKey(automatic = false) {
- const generation = aeroModalGeneration, request = ++aeroPSKRequest;
- const input = document.getElementById('aerotun-modal-psk'), previous = input.value;
- try {
- const res = await fetch(`${API_BASE}/vpn/aerotun/genkey`);
- if (!res.ok) throw new Error(await responseError(res));
- const data = await res.json();
- if (generation !== aeroModalGeneration || request !== aeroPSKRequest || (automatic && input.value !== previous)) return;
- input.value = data.key;
- if (!automatic) showToast('Key Generated', 'Share this PSK securely with the peer before enabling', 'success');
- } catch (err) {
- if (generation === aeroModalGeneration && request === aeroPSKRequest) showToast('Key Generation Failed', err.message, 'error');
- }
- }
- function updateAeroTUNSetupHint() {
- const version = document.getElementById('aerotun-modal-protocol').value;
- const key = document.getElementById('aerotun-modal-public').value;
- const peer = document.getElementById('aerotun-modal-peerkey').value.trim();
- const hint = document.getElementById('aerotun-setup-hint');
- document.getElementById('aerotun-v3-fields').classList.toggle('hidden', version !== '3');
- if (!hint) return;
- hint.innerText = version !== '3' ? 'Legacy v2 uses a shared PSK. Both endpoints must use the same protocol.' : !key ? (document.getElementById('aerotun-modal-id').value ? 'Save this existing tunnel disabled to create its v3 identity, then exchange public keys.' : 'Generating the local identity. You can fill in the other settings while you wait.') : !peer ? 'Copy the local public key to the peer and paste its public key here. Use the same PSK on both endpoints; save disabled if the peer key is not ready.' : 'Check reciprocal addresses, allowed peer source prefixes and the shared PSK before enabling. Allowed prefixes do not create LAN routes.';
- }
- async function copyAeroTUNPublicKey() {
- const input = document.getElementById('aerotun-modal-public');
- if (!input.value) { showToast('Key Not Ready', 'Wait for the local identity or retry key generation.', 'info'); return; }
- try {
- await navigator.clipboard.writeText(input.value);
- showToast('Public Key Copied', 'Paste it into the other endpoint’s pinned peer key', 'success');
- } catch {
- input.focus(); input.select();
- showToast('Copy Public Key', 'Key selected; press Ctrl+C to copy', 'info');
- }
- }
- async function copyAeroTUNPSK() {
- const input = document.getElementById('aerotun-modal-psk');
- if (!input.value) { showToast('PSK Not Available', 'Generate or enter a PSK to copy it. Existing keys are not displayed.', 'info'); return; }
- try { await navigator.clipboard.writeText(input.value); showToast('PSK Copied', 'Share it securely with the peer.', 'success'); }
- catch { input.type = 'text'; input.focus(); input.select(); showToast('Copy PSK', 'Key selected; press Ctrl+C to copy.', 'info'); }
- }
- function openAddAeroTUNModal() {
- if (aeroSaving) return;
- aeroModalGeneration++; discardAeroIdentityDraft(aeroIdentityDraft); aeroIdentityDraft = '';
- const tunnels = state.aerotunTunnels || [];
- const usedNames = new Set(tunnels.map(t => t.name));
- const usedPorts = new Set(tunnels.map(t => Number(t.listen_port)));
- let index = 0; while (index < 256 && (usedNames.has(`aerotun${index}`) || usedPorts.has(51830 + index) || tunnels.some(t => (t.local_address || '').startsWith(`10.99.${index}.`)))) index++;
- if (index >= 256) index = 0;
- document.getElementById('aerotun-modal-title').innerText = 'Add AeroTUN Interface';
- document.getElementById('aerotun-modal-id').value = '';
- document.getElementById('aerotun-modal-protocol').value='3';
- document.getElementById('aerotun-modal-public').value='';
- document.getElementById('aerotun-modal-peerkey').value='';
- document.getElementById('aerotun-modal-allowed').value=`10.99.${index}.2/32`;
- document.getElementById('aerotun-modal-name').value = `aerotun${index}`;
- document.getElementById('aerotun-modal-mode').value = 'server';
- document.getElementById('aerotun-modal-port').value = 51830 + index;
- document.getElementById('aerotun-modal-endpoint').value = '';
- document.getElementById('aerotun-modal-local').value = `10.99.${index}.1/24`;
- document.getElementById('aerotun-modal-peer').value = `10.99.${index}.2/24`;
- document.getElementById('aerotun-modal-peer').dataset.allowedDefault = `10.99.${index}.2/32`;
- document.getElementById('aerotun-modal-psk').value = '';
- document.getElementById('aerotun-modal-mtu').value = '1420';
- document.getElementById('aerotun-modal-comment').value = '';
- document.getElementById('aerotun-modal-compression').checked = false;
- document.getElementById('aerotun-modal-defroute').checked = false;
- document.getElementById('aerotun-modal-disabled').checked = true;
- document.getElementById('aerotun-modal-psk').type = 'password';
- document.getElementById('aerotun-modal-psk').placeholder = 'Generate or enter the shared key';
- onAeroTUNModeChange();
- updateAeroTUNSetupHint();
- document.getElementById('aerotun-modal').classList.remove('hidden');
- generateAeroTUNKey(true);
- generateAeroTUNIdentity();
- }
- function openEditAeroTUNModal(id) {
- if (aeroSaving) return;
- const t = (state.aerotunTunnels || []).find(tun => tun.id === id);
- if (!t) return;
- aeroModalGeneration++; discardAeroIdentityDraft(aeroIdentityDraft); aeroIdentityDraft = '';
- document.getElementById('aerotun-retry-identity').classList.add('hidden');
- document.getElementById('aerotun-modal-title').innerText = `Edit AeroTUN Interface (${t.name})`;
- document.getElementById('aerotun-modal-id').value = t.id;
- document.getElementById('aerotun-modal-protocol').value=String(t.protocol_version || 2);
- document.getElementById('aerotun-modal-public').value=t.public_key || '';
- document.getElementById('aerotun-modal-peerkey').value=t.peer_public_key || '';
- document.getElementById('aerotun-modal-allowed').value=(t.allowed_ips || []).join(', ');
- document.getElementById('aerotun-modal-name').value = t.name;
- document.getElementById('aerotun-modal-mode').value = t.mode || 'server';
- document.getElementById('aerotun-modal-port').value = t.listen_port || '';
- document.getElementById('aerotun-modal-endpoint').value = t.remote_endpoint || '';
- document.getElementById('aerotun-modal-local').value = t.local_address || '';
- document.getElementById('aerotun-modal-peer').value = t.peer_address || '';
- const peerHost = (t.peer_address || '').split('/')[0];
- document.getElementById('aerotun-modal-peer').dataset.allowedDefault = peerHost ? `${peerHost}/${peerHost.includes(':') ? 128 : 32}` : '';
- document.getElementById('aerotun-modal-psk').value = '';
- document.getElementById('aerotun-modal-psk').type = 'password';
- document.getElementById('aerotun-modal-psk').placeholder = t.has_psk ? 'Leave blank to keep the existing key' : 'New random 256-bit PSK';
- document.getElementById('aerotun-modal-mtu').value = t.configured_mtu || t.mtu || 1420;
- document.getElementById('aerotun-modal-comment').value = t.comment || '';
- document.getElementById('aerotun-modal-compression').checked = !!t.compression;
- document.getElementById('aerotun-modal-defroute').checked = !!t.default_route;
- document.getElementById('aerotun-modal-disabled').checked = !!t.disabled;
- onAeroTUNModeChange();
- updateAeroTUNSetupHint();
- document.getElementById('aerotun-modal').classList.remove('hidden');
- }
- function closeAeroTUNModal() {
- if (aeroSaving) return;
- aeroModalGeneration++; discardAeroIdentityDraft(aeroIdentityDraft); aeroIdentityDraft = '';
- document.getElementById('aerotun-modal-psk').value = '';
- document.getElementById('aerotun-modal').classList.add('hidden');
- }
- async function submitSaveAeroTUN(e) {
- e.preventDefault();
- if (aeroSaving) return;
- const id = document.getElementById('aerotun-modal-id').value;
- const name = document.getElementById('aerotun-modal-name').value.trim();
- const mode = document.getElementById('aerotun-modal-mode').value;
- const port = parseInt(document.getElementById('aerotun-modal-port').value) || 0;
- const endpoint = document.getElementById('aerotun-modal-endpoint').value.trim();
- const local = document.getElementById('aerotun-modal-local').value.trim();
- const peer = document.getElementById('aerotun-modal-peer').value.trim();
- const psk = document.getElementById('aerotun-modal-psk').value.trim();
- const mtuValue = document.getElementById('aerotun-modal-mtu').value;
- const mtu = mtuValue === '' ? 1420 : Number(mtuValue);
- const comment = document.getElementById('aerotun-modal-comment').value.trim();
- const compression = document.getElementById('aerotun-modal-compression').checked;
- const defaultRoute = document.getElementById('aerotun-modal-defroute').checked;
- const disabled = document.getElementById('aerotun-modal-disabled').checked;
- if (mode === 'client' && !endpoint) {
- showToast('Validation Error', 'Remote endpoint (host:port) is required in client mode', 'error');
- return;
- }
- if (defaultRoute && (mode !== 'client' || !endpoint)) {
- showToast('Validation Error', 'Default route requires client mode and a fixed remote endpoint.', 'error');
- return;
- }
- if (!Number.isInteger(mtu) || mtu < 576 || mtu > 9000) {
- showToast('Validation Error', 'MTU must be between 576 and 9000.', 'error');
- return;
- }
- const version = parseInt(document.getElementById('aerotun-modal-protocol').value, 10);
- if (version === 3 && !id && !aeroIdentityDraft) {
- showToast('Local Key Not Ready', 'Wait for the local identity or retry key generation before saving.', 'error');
- return;
- }
- if (version === 3 && !document.getElementById('aerotun-modal-allowed').value.trim()) {
- showToast('Allowed Prefix Required', 'Enter at least one allowed peer source prefix, such as the peer tunnel IP /32.', 'error');
- document.getElementById('aerotun-modal-allowed').focus();
- return;
- }
- if (version === 3 && !disabled && !document.getElementById('aerotun-modal-peerkey').value.trim()) {
- showToast('Peer Key Required', 'Enter the peer public key, or save this tunnel disabled until it is available.', 'error');
- return;
- }
- if (!psk && !id) {
- showToast('Validation Error', 'Pre-shared key (PSK) is required', 'error');
- return;
- }
- aeroSaving = true;
- const submit = document.querySelector('#aerotun-modal button[type="submit"]');
- if (submit) submit.disabled = true;
- try {
- const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- protocol_version:parseInt(document.getElementById('aerotun-modal-protocol').value,10),
- identity_draft_id: version === 3 && !id ? aeroIdentityDraft : '',
- peer_public_key:document.getElementById('aerotun-modal-peerkey').value.trim(),
- allowed_ips:document.getElementById('aerotun-modal-allowed').value.split(',').map(s=>s.trim()).filter(Boolean),
- id,
- name,
- mode,
- listen_port: port,
- remote_endpoint: endpoint,
- local_address: local,
- peer_address: peer,
- psk,
- mtu,
- compression,
- default_route: defaultRoute,
- comment,
- disabled
- })
- });
- if (res.ok) {
- await res.json();
- if (version !== 3) discardAeroIdentityDraft(aeroIdentityDraft);
- aeroIdentityDraft = '';
- aeroSaving = false;
- closeAeroTUNModal();
- await loadAeroTUN(false);
- showToast('AeroTUN Saved', disabled ? 'Configuration saved; tunnel is disabled' : 'Configuration saved; waiting for authenticated peer traffic', 'success');
- fetchData(false);
- } else {
- const err = await responseError(res);
- if (err.includes('configuration saved but tunnel failed to start')) {
- aeroIdentityDraft = '';
- aeroSaving = false;
- closeAeroTUNModal();
- await loadAeroTUN(false);
- showToast('Saved, but not started', err, 'error');
- } else showToast('Error Saving Tunnel', err, 'error');
- }
- } catch (err) {
- showToast('Network Error', err.message, 'error');
- } finally {
- aeroSaving = false;
- if (submit) submit.disabled = false;
- }
- }
- async function startAeroTUNTunnel(id) {
- try {
- const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/start`, { method: 'POST' });
- if (res.ok) {
- showToast('AeroTUN Started', 'Interface started; connection is confirmed by authenticated peer traffic', 'info');
- loadAeroTUN(false);
- fetchData(false);
- } else {
- const err = await res.text();
- showToast('Failed to Start', err, 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function stopAeroTUNTunnel(id) {
- try {
- const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/stop`, { method: 'POST' });
- if (res.ok) {
- showToast('AeroTUN Stopped', 'Tunnel stopped', 'info');
- loadAeroTUN(false);
- fetchData(false);
- } else {
- const err = await res.text();
- showToast('Failed to Stop', err, 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function toggleAeroTUNState(id, disabled) {
- try {
- const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/state`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ disabled })
- });
- if (res.ok) {
- showToast('State Updated', disabled ? 'Tunnel disabled' : 'Tunnel enabled', 'info');
- loadAeroTUN(false);
- fetchData(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deleteAeroTUN(id) {
- if (!confirm('Are you sure you want to delete this AeroTUN tunnel?')) return;
- try {
- const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}`, { method: 'DELETE' });
- if (res.ok) {
- showToast('Deleted', 'AeroTUN tunnel removed', 'success');
- loadAeroTUN(false);
- fetchData(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // ======================== PPP Central Hub & Servers ========================
- function switchPPPSubTab(tab) {
- state.pppSubTab = tab;
- const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
- tabs.forEach(t => {
- const panel = document.getElementById(`ppp-subtab-${t}`);
- const btn = document.getElementById(`ppp-subtab-btn-${t}`);
- if (panel) {
- if (t === tab) panel.classList.remove('hidden');
- else panel.classList.add('hidden');
- }
- if (btn) {
- if (t === tab) {
- 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';
- } else {
- 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';
- }
- }
- });
- const addBtn = document.getElementById('ppp-primary-add-btn');
- if (addBtn) {
- if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
- else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
- else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
- else addBtn.innerHTML = '<span>Save Config</span>';
- }
- if (tab === 'active') loadPPPSessions();
- }
- function openCurrentPPPModal() {
- if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
- else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
- else if (state.pppSubTab === 'active') loadPPPSessions();
- else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
- else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
- else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
- }
- async function loadPPP(populateDropdowns = true) {
- await Promise.all([
- loadPPPSecrets(),
- loadPPPProfiles(),
- loadPPPServers(),
- loadPPPSessions()
- ]);
- }
- async function loadPPPSecrets() {
- try {
- const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
- const data = await res.json();
- state.pppSecrets = Array.isArray(data) ? data : [];
- const b = document.getElementById('ppp-badge-secrets');
- if (b) b.innerText = state.pppSecrets.length;
- const b2 = document.getElementById('secrets-count-badge');
- if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
- renderPPPSecrets();
- } catch (err) {
- console.error('Failed to load PPP secrets:', err);
- }
- }
- function renderPPPSecrets() {
- const tbody = document.getElementById('secrets-table-body');
- const empty = document.getElementById('secrets-empty');
- if (!tbody) return;
- tbody.innerHTML = '';
- const secrets = state.pppSecrets || [];
- if (secrets.length === 0) {
- empty?.classList.remove('hidden');
- return;
- }
- empty?.classList.add('hidden');
- secrets.forEach(s => {
- const tr = document.createElement('tr');
- tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
- tr.innerHTML = `
- <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
- <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
- <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
- <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
- <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
- <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
- <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
- <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
- <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>
- <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
- <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
- </td>
- `;
- tbody.appendChild(tr);
- });
- }
- async function loadPPPProfiles() {
- try {
- const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
- const data = await res.json();
- state.pppProfiles = Array.isArray(data) ? data : [];
- const b = document.getElementById('ppp-badge-profiles');
- if (b) b.innerText = state.pppProfiles.length;
- const b2 = document.getElementById('profiles-count-badge');
- if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
- // Populate profile selects across modals
- const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
- selects.forEach(sid => {
- const el = document.getElementById(sid);
- if (!el) return;
- const cur = el.value;
- el.innerHTML = '';
- state.pppProfiles.forEach(p => {
- const opt = document.createElement('option');
- opt.value = p.name;
- opt.innerText = `${p.name} (${p.remote_address})`;
- if (p.name === cur) opt.selected = true;
- el.appendChild(opt);
- });
- });
- renderPPPProfiles();
- } catch (err) {
- console.error('Failed to load PPP profiles:', err);
- }
- }
- function renderPPPProfiles() {
- const tbody = document.getElementById('profiles-table-body');
- if (!tbody) return;
- tbody.innerHTML = '';
- (state.pppProfiles || []).forEach(p => {
- const isDefault = p.name.startsWith('default');
- const tr = document.createElement('tr');
- tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
- tr.innerHTML = `
- <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
- <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
- <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
- <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
- <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
- <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>
- <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
- <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
- ${!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>`}
- </td>
- `;
- tbody.appendChild(tr);
- });
- }
- async function loadPPPServers() {
- try {
- const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
- fetch(`${API_BASE}/vpn/servers/pppoe`),
- fetch(`${API_BASE}/vpn/servers/pptp`),
- fetch(`${API_BASE}/vpn/servers/l2tp`),
- fetch(`${API_BASE}/vpn/servers/ipsec`)
- ]);
- if (pppoeRes.ok) {
- state.pppoeServer = await pppoeRes.json();
- const s = state.pppoeServer;
- document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
- document.getElementById('pppoe-server-name').value = s.service_name || 'debtik-pppoe';
- populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
- document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
- document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
- document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
- const pill = document.getElementById('pppoe-server-status-pill');
- if (pill) {
- pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
- 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';
- }
- setDotBadge('ppp-badge-pppoe-state', s.running);
- }
- if (pptpRes.ok) {
- state.pptpServer = await pptpRes.json();
- const s = state.pptpServer;
- document.getElementById('pptp-server-enabled').checked = !!s.enabled;
- document.getElementById('pptp-server-port').value = s.port || 1723;
- document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
- document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
- const pill = document.getElementById('pptp-server-status-pill');
- if (pill) {
- pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
- 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';
- }
- setDotBadge('ppp-badge-pptp-state', s.running);
- }
- if (l2tpRes.ok) {
- state.l2tpServer = await l2tpRes.json();
- const s = state.l2tpServer;
- document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
- document.getElementById('l2tp-server-port').value = s.port || 1701;
- document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
- document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
- document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
- const pill = document.getElementById('l2tp-server-status-pill');
- if (pill) {
- pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
- 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';
- }
- setDotBadge('ppp-badge-l2tp-state', s.running);
- }
- if (ipsecRes.ok) {
- state.ipsecServer = await ipsecRes.json();
- const s = state.ipsecServer;
- const modalEn = document.getElementById('modal-ipsec-server-enabled');
- if (modalEn) modalEn.checked = !!s.enabled;
- const modalPsk = document.getElementById('modal-ipsec-server-psk');
- if (modalPsk) modalPsk.value = s.preshared_key || '';
- const modalPool = document.getElementById('modal-ipsec-server-pool');
- if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
- const modalDns = document.getElementById('modal-ipsec-server-dns');
- if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
- const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
- if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
- const pill = document.getElementById('modal-ipsec-server-status');
- if (pill) {
- pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
- 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';
- }
- }
- } catch (err) {
- console.error('Failed to load VPN servers:', err);
- }
- }
- async function loadPPPSessions() {
- try {
- const res = await fetch(`${API_BASE}/vpn/ppp/active`);
- const data = await res.json();
- state.pppActiveSessions = Array.isArray(data) ? data : [];
- const b = document.getElementById('ppp-badge-active');
- if (b) b.innerText = state.pppActiveSessions.length;
- const sideB = document.getElementById('badge-ppp-sessions');
- if (sideB) sideB.innerText = state.pppActiveSessions.length;
- renderPPPSessions();
- } catch (err) {
- console.error('Failed to load active PPP sessions:', err);
- }
- }
- function renderPPPSessions() {
- const tbody = document.getElementById('active-ppp-table-body');
- const empty = document.getElementById('active-ppp-empty');
- if (!tbody) return;
- tbody.innerHTML = '';
- const list = state.pppActiveSessions || [];
- if (list.length === 0) {
- empty?.classList.remove('hidden');
- return;
- }
- empty?.classList.add('hidden');
- list.forEach(s => {
- const tr = document.createElement('tr');
- tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
- tr.innerHTML = `
- <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
- <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
- <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
- <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
- <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
- <td class="py-2.5 px-3 text-[11px]">
- <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
- <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
- </td>
- <td class="py-2.5 px-3 text-right font-sans">
- <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
- </td>
- `;
- tbody.appendChild(tr);
- });
- }
- async function disconnectPPPSession(iface) {
- if (!confirm(`Disconnect session ${iface}?`)) return;
- try {
- const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
- if (res.ok) {
- showToast('Disconnected', `Session ${iface} terminated`, 'info');
- loadPPPSessions();
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // PPP Secret Modal handlers
- function openAddPPPSecretModal() {
- document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
- document.getElementById('secret-modal-id').value = '';
- document.getElementById('secret-modal-name').value = '';
- document.getElementById('secret-modal-password').value = '';
- document.getElementById('secret-modal-service').value = 'any';
- document.getElementById('secret-modal-profile').value = 'default';
- document.getElementById('secret-modal-local').value = '';
- document.getElementById('secret-modal-remote').value = '';
- document.getElementById('secret-modal-comment').value = '';
- document.getElementById('secret-modal-disabled').checked = false;
- document.getElementById('ppp-secret-modal').classList.remove('hidden');
- }
- function openEditPPPSecretModal(id) {
- const s = (state.pppSecrets || []).find(sec => sec.id === id);
- if (!s) return;
- document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
- document.getElementById('secret-modal-id').value = s.id;
- document.getElementById('secret-modal-name').value = s.name;
- document.getElementById('secret-modal-password').value = s.password;
- document.getElementById('secret-modal-service').value = s.service || 'any';
- document.getElementById('secret-modal-profile').value = s.profile || 'default';
- document.getElementById('secret-modal-local').value = s.local_address || '';
- document.getElementById('secret-modal-remote').value = s.remote_address || '';
- document.getElementById('secret-modal-comment').value = s.comment || '';
- document.getElementById('secret-modal-disabled').checked = !!s.disabled;
- document.getElementById('ppp-secret-modal').classList.remove('hidden');
- }
- function closePPPSecretModal() {
- document.getElementById('ppp-secret-modal').classList.add('hidden');
- }
- async function submitSavePPPSecret(e) {
- e.preventDefault();
- const id = document.getElementById('secret-modal-id').value;
- const name = document.getElementById('secret-modal-name').value.trim();
- const password = document.getElementById('secret-modal-password').value.trim();
- const service = document.getElementById('secret-modal-service').value;
- const profile = document.getElementById('secret-modal-profile').value;
- const local = document.getElementById('secret-modal-local').value.trim();
- const remote = document.getElementById('secret-modal-remote').value.trim();
- const comment = document.getElementById('secret-modal-comment').value.trim();
- const disabled = document.getElementById('secret-modal-disabled').checked;
- try {
- const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- id,
- name,
- password,
- service,
- profile,
- local_address: local,
- remote_address: remote,
- comment,
- disabled
- })
- });
- if (res.ok) {
- showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
- closePPPSecretModal();
- loadPPPSecrets();
- } else {
- const err = await res.json();
- showToast('Error', err.message, 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function togglePPPSecretState(id, disabled) {
- try {
- const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ disabled })
- });
- if (res.ok) {
- showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
- loadPPPSecrets();
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deletePPPSecret(id) {
- if (!confirm('Are you sure you want to delete this secret account?')) return;
- try {
- const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
- if (res.ok) {
- showToast('Deleted', 'Secret account removed', 'success');
- loadPPPSecrets();
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // PPP Profile Modal handlers
- function openAddPPPProfileModal() {
- document.getElementById('profile-modal-name').value = '';
- document.getElementById('profile-modal-local').value = '10.10.10.1';
- document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
- document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
- document.getElementById('profile-modal-encryption').value = 'required';
- document.getElementById('profile-modal-onlyone').checked = true;
- document.getElementById('profile-modal-comment').value = '';
- document.getElementById('ppp-profile-modal').classList.remove('hidden');
- }
- function closePPPProfileModal() {
- document.getElementById('ppp-profile-modal').classList.add('hidden');
- }
- async function submitSavePPPProfile(e) {
- e.preventDefault();
- const name = document.getElementById('profile-modal-name').value.trim();
- const local = document.getElementById('profile-modal-local').value.trim();
- const remote = document.getElementById('profile-modal-remote').value.trim();
- const dns = document.getElementById('profile-modal-dns').value.trim();
- const enc = document.getElementById('profile-modal-encryption').value;
- const onlyone = document.getElementById('profile-modal-onlyone').checked;
- const comment = document.getElementById('profile-modal-comment').value.trim();
- try {
- const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- id: name,
- name,
- local_address: local,
- remote_address: remote,
- dns_servers: dns,
- use_encryption: enc,
- only_one: onlyone,
- comment
- })
- });
- if (res.ok) {
- showToast('Profile Saved', `PPP profile ${name} created`, 'success');
- closePPPProfileModal();
- loadPPPProfiles();
- } else {
- const err = await res.json();
- showToast('Error', err.message, 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deletePPPProfile(name) {
- if (!confirm(`Delete PPP profile ${name}?`)) return;
- try {
- const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
- if (res.ok) {
- showToast('Deleted', 'Profile removed', 'success');
- loadPPPProfiles();
- } else {
- const err = await res.json();
- showToast('Error', err.message, 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // Server Config submissions
- async function savePPPoEServerConfig(e) {
- e.preventDefault();
- const enabled = document.getElementById('pppoe-server-enabled').checked;
- const name = document.getElementById('pppoe-server-name').value.trim();
- const iface = document.getElementById('pppoe-server-iface').value;
- const profile = document.getElementById('pppoe-server-profile').value;
- const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
- const onesession = document.getElementById('pppoe-server-onesession').checked;
- try {
- const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- enabled,
- service_name: name,
- interface: iface,
- default_profile: profile,
- max_mtu: mtu,
- max_mru: mtu,
- one_session_per_host: onesession
- })
- });
- if (res.ok) {
- showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
- loadPPPServers();
- fetchData(false);
- } else {
- const err = await res.json();
- showToast('Error', err.message, 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function savePPTPServerConfig(e) {
- e.preventDefault();
- const enabled = document.getElementById('pptp-server-enabled').checked;
- const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
- const profile = document.getElementById('pptp-server-profile').value;
- const mppe = document.getElementById('pptp-server-mppe').checked;
- try {
- const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- enabled,
- port,
- default_profile: profile,
- require_mppe: mppe
- })
- });
- if (res.ok) {
- showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
- loadPPPServers();
- fetchData(false);
- } else {
- const err = await res.json();
- showToast('Error', err.message, 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function saveL2TPServerConfig(e) {
- e.preventDefault();
- const enabled = document.getElementById('l2tp-server-enabled').checked;
- const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
- const profile = document.getElementById('l2tp-server-profile').value;
- const useipsec = document.getElementById('l2tp-server-useipsec').value;
- const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
- try {
- const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- enabled,
- port,
- default_profile: profile,
- use_ipsec: useipsec,
- ipsec_secret: psk
- })
- });
- if (res.ok) {
- showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
- loadPPPServers();
- fetchData(false);
- } else {
- const err = await res.json();
- showToast('Error', err.message, 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // IPSec Server Modal
- function openIPSecServerModal() {
- loadPPPServers();
- document.getElementById('ipsec-server-modal').classList.remove('hidden');
- }
- function closeIPSecServerModal() {
- document.getElementById('ipsec-server-modal').classList.add('hidden');
- }
- async function submitSaveIPSecServer(e) {
- e.preventDefault();
- const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
- const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
- const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
- const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
- const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
- try {
- const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- enabled,
- preshared_key: psk,
- pool_address: pool,
- dns_servers: dns,
- local_subnet: subnet
- })
- });
- if (res.ok) {
- showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
- closeIPSecServerModal();
- loadPPPServers();
- fetchData(false);
- } else {
- const err = await res.json();
- showToast('Error', err.message, 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // WireGuard Client Config Viewer
- let currentWGClientConf = '';
- async function openWGClientConfModal(iface, clientIP) {
- try {
- const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- interface: iface,
- address: clientIP || '10.10.0.2/32',
- dns: '1.1.1.1, 8.8.8.8'
- })
- });
- if (res.ok) {
- const data = await res.json();
- currentWGClientConf = data.config;
- document.getElementById('wg-client-conf-text').value = currentWGClientConf;
- document.getElementById('wg-client-conf-modal').classList.remove('hidden');
- } else {
- const err = await res.json();
- showToast('Error', err.message, 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- function closeWGClientConfModal() {
- document.getElementById('wg-client-conf-modal').classList.add('hidden');
- }
- function copyWGClientConf() {
- if (!currentWGClientConf) return;
- copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
- }
- function downloadWGClientConf() {
- if (!currentWGClientConf) return;
- const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
- const a = document.createElement('a');
- a.href = URL.createObjectURL(blob);
- a.download = 'wireguard-client.conf';
- document.body.appendChild(a);
- a.click();
- document.body.removeChild(a);
- showToast('Downloaded', 'wireguard-client.conf saved', 'success');
- }
- // =========================================================================
- // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
- // =========================================================================
- state.activeDynSubTab = 'bgp-peers';
- state.activeBgpSubTab = 'bgp-peers';
- state.activeOspfTab = 'instances';
- state.bgpInstance = null;
- state.bgpPeers = [];
- state.bgpNets = [];
- state.bgpRoutes = [];
- state.ospfInstance = null;
- state.ospfInstances = [];
- state.ospfAreas = [];
- state.ospfAreaRanges = [];
- state.ospfTemplates = [];
- state.ospfLiveInterfaces = [];
- state.ospfStaticNbrs = [];
- state.ospfNeighbors = [];
- state.ospfLSA = [];
- state.ospfRoutes = [];
- state.selectedOspfRow = {
- instances: null,
- areas: null,
- 'area-ranges': null,
- templates: null,
- interfaces: null,
- 'static-nbrs': null,
- neighbors: null,
- lsa: null,
- };
- state.ospfSort = {
- instances: { col: 'name', asc: true },
- areas: { col: 'name', asc: true },
- ranges: { col: 'area', asc: true },
- templates: { col: 'interfaces', asc: true },
- live_ifaces: { col: 'interface', asc: true },
- snbrs: { col: 'address', asc: true },
- neighbors: { col: 'address', asc: true },
- lsa: { col: 'instance', asc: true },
- };
- function switchBgpSubTab(subTab) {
- state.activeBgpSubTab = subTab;
- const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes'];
- tabs.forEach(t => {
- const el = document.getElementById(`dyn-subtab-${t}`);
- const btn = document.getElementById(`bgp-subtab-btn-${t}`);
- if (el) el.classList.toggle('hidden', t !== subTab);
- if (btn) {
- if (t === subTab) {
- 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';
- } else {
- 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';
- }
- }
- });
- }
- function switchOspfTab(tabName) {
- state.activeOspfTab = tabName;
- const tabs = ['instances', 'areas', 'area-ranges', 'templates', 'interfaces', 'static-nbrs', 'neighbors', 'lsa'];
- tabs.forEach(t => {
- const pane = document.getElementById(`ospf-pane-${t}`);
- const btn = document.getElementById(`ospf-tab-btn-${t}`);
- if (pane) pane.classList.toggle('hidden', t !== tabName);
- if (btn) {
- if (t === tabName) {
- 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';
- } else {
- 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';
- }
- }
- });
- }
- function switchOspfSubTab(tab) {
- // Legacy alias
- if (tab === 'ospf-ifaces') switchOspfTab('templates');
- else if (tab === 'ospf-areas') switchOspfTab('areas');
- else if (tab === 'ospf-nbrs') switchOspfTab('neighbors');
- else switchOspfTab('instances');
- }
- function switchDynSubTab(subTab) {
- if (subTab.startsWith('bgp')) {
- if (state.activeTab !== 'bgp') navigate('bgp');
- switchBgpSubTab(subTab);
- } else if (subTab.startsWith('ospf')) {
- if (state.activeTab !== 'ospf') navigate('ospf');
- switchOspfTab('instances');
- }
- }
- async function loadDynamicRouting(showToastMsg = false) {
- try {
- const fetchSafeJson = async (url) => {
- try {
- const r = await fetch(url);
- return r.ok ? await r.json() : null;
- } catch (e) {
- return null;
- }
- };
- const [
- sum, bgpInst, bgpPeers, bgpNets, bgpRoutes,
- ospfInsts, ospfAreas, ospfRanges, ospfTemplates, ospfLiveIfaces, ospfStaticNbrs, ospfNbrs, ospfLsa, filters,
- selectRules, commLists, asLists
- ] = await Promise.all([
- fetchSafeJson(`${API_BASE}/routing/dynamic/summary`),
- fetchSafeJson(`${API_BASE}/routing/bgp/instance`),
- fetchSafeJson(`${API_BASE}/routing/bgp/peers`),
- fetchSafeJson(`${API_BASE}/routing/bgp/networks`),
- fetchSafeJson(`${API_BASE}/routing/bgp/routes`),
- fetchSafeJson(`${API_BASE}/routing/ospf/instances`),
- fetchSafeJson(`${API_BASE}/routing/ospf/areas`),
- fetchSafeJson(`${API_BASE}/routing/ospf/area-ranges`),
- fetchSafeJson(`${API_BASE}/routing/ospf/templates`),
- fetchSafeJson(`${API_BASE}/routing/ospf/interfaces-live`),
- fetchSafeJson(`${API_BASE}/routing/ospf/static-neighbors`),
- fetchSafeJson(`${API_BASE}/routing/ospf/neighbors`),
- fetchSafeJson(`${API_BASE}/routing/ospf/lsa`),
- fetchSafeJson(`${API_BASE}/routing/filters`),
- fetchSafeJson(`${API_BASE}/routing/filters/community-lists`),
- fetchSafeJson(`${API_BASE}/routing/filters/as-lists`)
- ]);
- if (sum) state.dynSummary = sum;
- if (bgpInst) state.bgpInstance = bgpInst;
- if (bgpPeers) state.bgpPeers = bgpPeers;
- if (bgpNets) state.bgpNets = bgpNets;
- if (bgpRoutes) state.bgpRoutes = bgpRoutes;
- if (ospfInsts) state.ospfInstances = ospfInsts;
- if (ospfAreas) state.ospfAreas = ospfAreas;
- if (ospfRanges) state.ospfAreaRanges = ospfRanges;
- if (ospfTemplates) state.ospfTemplates = ospfTemplates;
- if (ospfLiveIfaces) state.ospfLiveInterfaces = ospfLiveIfaces;
- if (ospfStaticNbrs) state.ospfStaticNbrs = ospfStaticNbrs;
- if (ospfNbrs) state.ospfNeighbors = ospfNbrs;
- if (ospfLsa) state.ospfLSA = ospfLsa;
- if (filters) state.routingFilters = filters;
- if (commLists) state.routingCommunityLists = commLists;
- if (asLists) state.routingASLists = asLists;
- try { renderBgpStatusPill(); } catch(e) { console.error('renderBgpStatusPill error:', e); }
- try { renderBgpPeers(); } catch(e) { console.error('renderBgpPeers error:', e); }
- try { renderBgpNetworks(); } catch(e) { console.error('renderBgpNetworks error:', e); }
- try { renderBgpRoutes(); } catch(e) { console.error('renderBgpRoutes error:', e); }
- try { renderOspfInstances(); } catch(e) { console.error('renderOspfInstances error:', e); }
- try { renderOspfAreas(); } catch(e) { console.error('renderOspfAreas error:', e); }
- try { renderOspfAreaRanges(); } catch(e) { console.error('renderOspfAreaRanges error:', e); }
- try { renderOspfTemplates(); } catch(e) { console.error('renderOspfTemplates error:', e); }
- try { renderOspfLiveInterfaces(); } catch(e) { console.error('renderOspfLiveInterfaces error:', e); }
- try { renderOspfStaticNbrs(); } catch(e) { console.error('renderOspfStaticNbrs error:', e); }
- try { renderOspfNeighbors(); } catch(e) { console.error('renderOspfNeighbors error:', e); }
- try { renderOspfLSA(); } catch(e) { console.error('renderOspfLSA error:', e); }
- try { renderRoutingFilters(); } catch(e) { console.error('renderRoutingFilters error:', e); }
- try { updateBadges(); } catch(e) { console.error('updateBadges error:', e); }
- if (showToastMsg) showToast('Refreshed', 'Dynamic routing telemetry updated', 'info');
- } catch (err) {
- console.error('Failed to load dynamic routing:', err);
- if (showToastMsg) showToast('Notice', 'Unable to refresh dynamic routing telemetry', 'warning');
- }
- }
- async function loadOspfAll() {
- await loadDynamicRouting(true);
- }
- function renderBgpStatusPill() {
- const pills = document.querySelectorAll('.bgp-live-status-pill');
- pills.forEach(pill => {
- const inst = state.bgpInstance;
- if (!inst || !inst.enabled) {
- pill.className = 'bgp-live-status-pill text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
- pill.innerText = 'BGP DISABLED';
- } else if (inst.running) {
- pill.className = 'bgp-live-status-pill text-[10px] px-2 py-0.5 rounded font-mono bg-purple-950 text-purple-300 border border-purple-800/60 font-semibold';
- pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
- } else {
- pill.className = 'bgp-live-status-pill text-[10px] px-2 py-0.5 rounded font-mono bg-amber-950 text-amber-300 border border-amber-800/60 font-semibold';
- pill.innerText = 'BGP STARTING...';
- }
- });
- }
- function renderBgpPeers() {
- const tbody = document.getElementById('bgp-peers-table-body');
- if (!tbody) return;
- const empty = document.getElementById('bgp-peers-empty');
- const countBadge = document.getElementById('bgp-peers-count-badge');
- const navBadge = document.getElementById('dyn-badge-bgp-peers');
- const peers = state.bgpPeers || [];
- if (countBadge) countBadge.innerText = `${peers.length} Peers`;
- if (navBadge) navBadge.innerText = peers.length;
- if (peers.length === 0) {
- tbody.innerHTML = '';
- if (empty) empty.classList.remove('hidden');
- return;
- }
- if (empty) empty.classList.add('hidden');
- const sig = peers.map(p => `${p.name}:${p.state}:${p.uptime}:${p.prefix_received}:${p.prefix_sent}:${p.disabled}`).join(';');
- if (tbody.dataset.sig === sig) return;
- tbody.dataset.sig = sig;
- tbody.innerHTML = peers.map(p => {
- let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
- let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
- let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
- let stateBadge = '';
- if (p.disabled) {
- 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>';
- } else if (p.state === 'Established') {
- 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>';
- } else if (p.state === 'Connect' || p.state === 'Active') {
- 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>`;
- } else {
- 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>`;
- }
- return `
- <tr class="hover:bg-slate-800/40 transition">
- <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
- <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
- <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
- <td class="py-2.5 px-3">
- <div class="font-bold text-slate-200">AS ${p.remote_as}</div>
- ${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>`}
- </td>
- <td class="py-2.5 px-3">${stateBadge}</td>
- <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
- <td class="py-2.5 px-3 text-slate-300">
- <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
- <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
- </td>
- <td class="py-2.5 px-3 font-mono text-[11px] whitespace-nowrap">
- ${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> ` : ''}
- ${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>` : ''}
- ${!p.in_filter && !p.out_filter ? '<span class="text-slate-600">-</span>' : ''}
- </td>
- <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
- <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
- <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'}">
- ${p.disabled ? 'Enable' : 'Disable'}
- </button>
- <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">
- Edit
- </button>
- <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">
- Delete
- </button>
- </td>
- </tr>
- `;
- }).join('');
- }
- function renderBgpNetworks() {
- const tbody = document.getElementById('bgp-nets-table-body');
- if (!tbody) return;
- const empty = document.getElementById('bgp-nets-empty');
- const countBadge = document.getElementById('bgp-nets-count-badge');
- const navBadge = document.getElementById('dyn-badge-bgp-nets');
- const nets = state.bgpNets || [];
- if (countBadge) countBadge.innerText = `${nets.length} Networks`;
- if (navBadge) navBadge.innerText = nets.length;
- if (nets.length === 0) {
- tbody.innerHTML = '';
- if (empty) empty.classList.remove('hidden');
- return;
- }
- if (empty) empty.classList.add('hidden');
- const sig = nets.map(n => `${n.network}:${n.disabled}:${n.comment}`).join(';');
- if (tbody.dataset.sig === sig) return;
- tbody.dataset.sig = sig;
- tbody.innerHTML = nets.map(n => `
- <tr class="hover:bg-slate-800/40 transition">
- <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
- <td class="py-2.5 px-3">
- ${n.disabled
- ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
- : '<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>'}
- </td>
- <td class="py-2.5 px-3">
- ${n.disabled
- ? '<span class="text-slate-600 font-mono text-[10px]">-</span>'
- : '<span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-cyan-300 border border-cyan-800/40 font-mono">blackhole (dist 255)</span>'}
- </td>
- <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
- <td class="py-2.5 px-3 text-right space-x-1 font-sans">
- <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">
- Delete
- </button>
- </td>
- </tr>
- `).join('');
- }
- function renderBgpRoutes() {
- const tbody = document.getElementById('bgp-routes-table-body');
- if (!tbody) return;
- const empty = document.getElementById('bgp-routes-empty');
- const countBadge = document.getElementById('bgp-routes-count-badge');
- const navBadge = document.getElementById('dyn-badge-bgp-routes');
- const routes = state.bgpRoutes || [];
- if (countBadge) countBadge.innerText = `${routes.length} Routes`;
- if (navBadge) navBadge.innerText = routes.length;
- if (routes.length === 0) {
- tbody.innerHTML = '';
- if (empty) empty.classList.remove('hidden');
- return;
- }
- if (empty) empty.classList.add('hidden');
- const sig = routes.map(r => `${r.prefix}:${r.next_hop}:${r.metric}:${r.path}`).join(';');
- if (tbody.dataset.sig === sig) return;
- tbody.dataset.sig = sig;
- tbody.innerHTML = routes.map(r => `
- <tr class="hover:bg-slate-800/40 transition">
- <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
- <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
- <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
- <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
- <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
- <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
- </tr>
- `).join('');
- }
- // =========================================================================
- // DEBTIK v7 OSPF TABLE RENDERING & SORTING
- // =========================================================================
- function sortOspfTable(tab, col) {
- if (!state.ospfSort) state.ospfSort = {};
- if (!state.ospfSort[tab]) state.ospfSort[tab] = { col: col, asc: true };
- if (state.ospfSort[tab].col === col) {
- state.ospfSort[tab].asc = !state.ospfSort[tab].asc;
- } else {
- state.ospfSort[tab].col = col;
- state.ospfSort[tab].asc = true;
- }
- const asc = state.ospfSort[tab].asc;
- let list = [];
- if (tab === 'instances') list = state.ospfInstances || [];
- else if (tab === 'areas') list = state.ospfAreas || [];
- else if (tab === 'ranges') list = state.ospfAreaRanges || [];
- else if (tab === 'templates') list = state.ospfTemplates || [];
- else if (tab === 'live_ifaces') list = state.ospfLiveInterfaces || [];
- else if (tab === 'snbrs') list = state.ospfStaticNbrs || [];
- else if (tab === 'neighbors') list = state.ospfNeighbors || [];
- else if (tab === 'lsa') list = state.ospfLSA || [];
- list.sort((a, b) => {
- let valA = a[col] ?? '';
- let valB = b[col] ?? '';
- if (typeof valA === 'number' && typeof valB === 'number') {
- return asc ? valA - valB : valB - valA;
- }
- return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
- });
- if (tab === 'instances') renderOspfInstances();
- else if (tab === 'areas') renderOspfAreas();
- else if (tab === 'ranges') renderOspfAreaRanges();
- else if (tab === 'templates') renderOspfTemplates();
- else if (tab === 'live_ifaces') renderOspfLiveInterfaces();
- else if (tab === 'snbrs') renderOspfStaticNbrs();
- else if (tab === 'neighbors') renderOspfNeighbors();
- else if (tab === 'lsa') renderOspfLSA();
- }
- function selectOspfRow(tab, id) {
- if (!state.selectedOspfRow) state.selectedOspfRow = {};
- state.selectedOspfRow[tab] = id;
- if (tab === 'instances') {
- renderOspfInstances();
- const btnEn = document.getElementById('btn-ospf-inst-enable');
- const btnDis = document.getElementById('btn-ospf-inst-disable');
- const btnRem = document.getElementById('btn-ospf-inst-remove');
- const btnCom = document.getElementById('btn-ospf-inst-comment');
- if (btnEn) btnEn.disabled = false;
- if (btnDis) btnDis.disabled = false;
- if (btnRem) btnRem.disabled = false;
- if (btnCom) btnCom.disabled = false;
- } else if (tab === 'areas') {
- renderOspfAreas();
- const btnEn = document.getElementById('btn-ospf-area-enable');
- const btnDis = document.getElementById('btn-ospf-area-disable');
- const btnRem = document.getElementById('btn-ospf-area-remove');
- const btnCom = document.getElementById('btn-ospf-area-comment');
- if (btnEn) btnEn.disabled = false;
- if (btnDis) btnDis.disabled = false;
- if (btnRem) btnRem.disabled = false;
- if (btnCom) btnCom.disabled = false;
- } else if (tab === 'ranges') {
- renderOspfAreaRanges();
- const btnEn = document.getElementById('btn-ospf-range-enable');
- const btnDis = document.getElementById('btn-ospf-range-disable');
- const btnRem = document.getElementById('btn-ospf-range-remove');
- const btnCom = document.getElementById('btn-ospf-range-comment');
- if (btnEn) btnEn.disabled = false;
- if (btnDis) btnDis.disabled = false;
- if (btnRem) btnRem.disabled = false;
- if (btnCom) btnCom.disabled = false;
- } else if (tab === 'templates') {
- renderOspfTemplates();
- const btnEn = document.getElementById('btn-ospf-tmpl-enable');
- const btnDis = document.getElementById('btn-ospf-tmpl-disable');
- const btnRem = document.getElementById('btn-ospf-tmpl-remove');
- const btnCom = document.getElementById('btn-ospf-tmpl-comment');
- if (btnEn) btnEn.disabled = false;
- if (btnDis) btnDis.disabled = false;
- if (btnRem) btnRem.disabled = false;
- if (btnCom) btnCom.disabled = false;
- } else if (tab === 'snbrs') {
- renderOspfStaticNbrs();
- const btnEn = document.getElementById('btn-ospf-snbr-enable');
- const btnDis = document.getElementById('btn-ospf-snbr-disable');
- const btnRem = document.getElementById('btn-ospf-snbr-remove');
- const btnCom = document.getElementById('btn-ospf-snbr-comment');
- if (btnEn) btnEn.disabled = false;
- if (btnDis) btnDis.disabled = false;
- if (btnRem) btnRem.disabled = false;
- if (btnCom) btnCom.disabled = false;
- }
- }
- // TAB 1: INSTANCES
- function renderOspfInstances() {
- const tbody = document.getElementById('ospf-instances-table-body');
- if (!tbody) return;
- const countEl = document.getElementById('ospf-instances-footer-count');
- const filter = (document.getElementById('filter-ospf-instances')?.value || '').toLowerCase();
- let list = state.ospfInstances || [];
- if (filter) {
- list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.router_id || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
- }
- if (countEl) countEl.innerText = list.length;
- const selId = state.selectedOspfRow?.instances;
- tbody.innerHTML = list.map((inst, idx) => {
- const isSel = inst.id === selId;
- const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
- const flagD = inst.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
- return `
- <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('instances', '${inst.id}')" ondblclick="openEditOspfInstanceModal('${inst.id}')">
- <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
- <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
- <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
- <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
- <span class="text-sky-400">↳</span> <span>${escapeHtml(inst.name || 'Default')}</span>
- </td>
- <td class="py-1.5 px-3">${inst.version || 2}</td>
- <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(inst.vrf || 'main')}</td>
- <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(inst.router_id || '192.168.131.56')}</td>
- </tr>
- `;
- }).join('');
- }
- // TAB 2: AREAS
- function renderOspfAreas() {
- const tbody = document.getElementById('ospf-areas-table-body');
- if (!tbody) return;
- const countEl = document.getElementById('ospf-areas-footer-count');
- const filter = (document.getElementById('filter-ospf-areas')?.value || '').toLowerCase();
- let list = state.ospfAreas || [];
- if (filter) {
- list = list.filter(a => (a.name || '').toLowerCase().includes(filter) || (a.area_id || '').toLowerCase().includes(filter) || (a.comment || '').toLowerCase().includes(filter));
- }
- if (countEl) countEl.innerText = list.length;
- const selId = state.selectedOspfRow?.areas;
- tbody.innerHTML = list.map((a, idx) => {
- const isSel = a.id === selId;
- const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
- const flagD = a.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
- return `
- <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('areas', '${a.id}')" ondblclick="openEditOspfAreaModal('${a.id}')">
- <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
- <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🌐'}</td>
- <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(a.comment || '')}</td>
- <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
- <span class="text-sky-400">↳</span> <span>${escapeHtml(a.name || 'Default')}</span>
- </td>
- <td class="py-1.5 px-3 text-slate-300">${escapeHtml(a.instance || 'Default')}</td>
- <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(a.area_id || '0.0.0.0')}</td>
- <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(a.area_type || 'default')}</td>
- </tr>
- `;
- }).join('');
- }
- // TAB 3: AREA RANGES
- function renderOspfAreaRanges() {
- const tbody = document.getElementById('ospf-ranges-table-body');
- if (!tbody) return;
- const countEl = document.getElementById('ospf-ranges-footer-count');
- const filter = (document.getElementById('filter-ospf-area-ranges')?.value || '').toLowerCase();
- let list = state.ospfAreaRanges || [];
- if (filter) {
- list = list.filter(r => (r.prefix || '').toLowerCase().includes(filter) || (r.area || '').toLowerCase().includes(filter) || (r.comment || '').toLowerCase().includes(filter));
- }
- if (countEl) countEl.innerText = list.length;
- const selId = state.selectedOspfRow?.['area-ranges'];
- tbody.innerHTML = list.map((r, idx) => {
- const isSel = r.id === selId;
- const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
- const flagD = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
- return `
- <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('ranges', '${r.id}')" ondblclick="openEditOspfAreaRangeModal('${r.id}')">
- <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
- <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🏷'}</td>
- <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(r.comment || '')}</td>
- <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(r.area || 'Default')}</td>
- <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(r.prefix || '')}</td>
- <td class="py-1.5 px-3">${r.cost || 1}</td>
- <td class="py-1.5 px-3">${r.advertise !== false ? 'yes' : 'no'}</td>
- </tr>
- `;
- }).join('');
- }
- // TAB 4: INTERFACE TEMPLATES
- function renderOspfTemplates() {
- const tbody = document.getElementById('ospf-templates-table-body');
- if (!tbody) return;
- const countEl = document.getElementById('ospf-templates-footer-count');
- const filter = (document.getElementById('filter-ospf-templates')?.value || '').toLowerCase();
- let list = state.ospfTemplates || [];
- if (filter) {
- list = list.filter(t => (t.interfaces || t.interface || '').toLowerCase().includes(filter) || (t.networks || t.network || '').toLowerCase().includes(filter) || (t.comment || '').toLowerCase().includes(filter));
- }
- if (countEl) countEl.innerText = list.length;
- const selId = state.selectedOspfRow?.templates;
- tbody.innerHTML = list.map((t, idx) => {
- const isSel = t.id === selId;
- const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
- const ifaces = t.interfaces || t.interface || 'all';
- const nets = t.networks || t.network || '';
- const flagD = t.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
- return `
- <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('templates', '${t.id}')" ondblclick="openEditOspfTemplateModal('${t.id}')">
- <td class="py-1.5 px-3 w-8 text-center text-slate-500 font-bold">${idx}</td>
- <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
- <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(t.comment || '')}</td>
- <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
- <span class="text-sky-400">↳</span> <span>${escapeHtml(ifaces)}</span>
- </td>
- <td class="py-1.5 px-3 text-slate-300">${escapeHtml(t.area || 'Default')}</td>
- <td class="py-1.5 px-3 font-mono text-sky-300">${escapeHtml(nets)}</td>
- <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(t.network_type || 'broadcast')}</td>
- <td class="py-1.5 px-3">${t.cost || 1}</td>
- <td class="py-1.5 px-3">${t.priority || 128}</td>
- <td class="py-1.5 px-3 text-slate-400">${escapeHtml(t.auth || t.auth_type || '')}</td>
- </tr>
- `;
- }).join('');
- }
- // TAB 5: LIVE INTERFACES
- function renderOspfLiveInterfaces() {
- const tbody = document.getElementById('ospf-live-interfaces-table-body');
- if (!tbody) return;
- const countEl = document.getElementById('ospf-live-interfaces-footer-count');
- const filter = (document.getElementById('filter-ospf-interfaces')?.value || '').toLowerCase();
- let list = state.ospfLiveInterfaces || [];
- if (filter) {
- list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.address || '').toLowerCase().includes(filter) || (i.state || '').toLowerCase().includes(filter));
- }
- if (countEl) countEl.innerText = list.length;
- tbody.innerHTML = list.map(i => `
- <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
- <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(i.flags || 'D')}</td>
- <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(i.interface || '')}</td>
- <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(i.address || '')}</td>
- <td class="py-1.5 px-3 text-slate-300">${escapeHtml(i.area || 'Default')}</td>
- <td class="py-1.5 px-3 text-center text-slate-400">${i.instance_id || 0}</td>
- <td class="py-1.5 px-3 font-mono text-amber-300 lowercase">${escapeHtml(i.state || 'waiting')}</td>
- <td class="py-1.5 px-3">${i.cost || 1}</td>
- <td class="py-1.5 px-3">${i.priority || 128}</td>
- </tr>
- `).join('');
- }
- // TAB 6: STATIC NEIGHBORS
- function renderOspfStaticNbrs() {
- const tbody = document.getElementById('ospf-snbrs-table-body');
- if (!tbody) return;
- const countEl = document.getElementById('ospf-snbrs-footer-count');
- const filter = (document.getElementById('filter-ospf-static-nbrs')?.value || '').toLowerCase();
- let list = state.ospfStaticNbrs || [];
- if (filter) {
- list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.area || '').toLowerCase().includes(filter) || (n.comment || '').toLowerCase().includes(filter));
- }
- if (countEl) countEl.innerText = list.length;
- const selId = state.selectedOspfRow?.['static-nbrs'];
- tbody.innerHTML = list.map((n, idx) => {
- const isSel = n.id === selId;
- const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
- const flagD = n.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
- return `
- <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('snbrs', '${n.id}')" ondblclick="openEditOspfStaticNbrModal('${n.id}')">
- <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
- <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '📡'}</td>
- <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
- <td class="py-1.5 px-3 font-semibold font-mono text-sky-300">${escapeHtml(n.address || '')}</td>
- <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
- <td class="py-1.5 px-3">${n.poll_interval || 120}s</td>
- <td class="py-1.5 px-3">${n.cost || 1}</td>
- </tr>
- `;
- }).join('');
- }
- // TAB 7: LIVE NEIGHBORS
- function renderOspfNeighbors() {
- const tbody = document.getElementById('ospf-neighbors-table-body');
- if (!tbody) return;
- const countEl = document.getElementById('ospf-neighbors-footer-count');
- const filter = (document.getElementById('filter-ospf-neighbors')?.value || '').toLowerCase();
- let list = state.ospfNeighbors || [];
- if (filter) {
- list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.state || '').toLowerCase().includes(filter) || (n.instance || '').toLowerCase().includes(filter));
- }
- if (countEl) countEl.innerText = list.length;
- tbody.innerHTML = list.map(n => `
- <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
- <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(n.flags || 'D')}</td>
- <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
- <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
- <span class="text-sky-400">↳</span> <span>${escapeHtml(n.instance || 'Default')}</span>
- </td>
- <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
- <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(n.address || '')}</td>
- <td class="py-1.5 px-3 font-mono font-bold text-emerald-400">${escapeHtml(n.state || 'Full')}</td>
- <td class="py-1.5 px-3 text-slate-400">${n.state_changes ?? 6}</td>
- </tr>
- `).join('');
- }
- // TAB 8: LINK-STATE DATABASE (LSA)
- function renderOspfLSA() {
- const tbody = document.getElementById('ospf-lsa-table-body');
- if (!tbody) return;
- const countEl = document.getElementById('ospf-lsa-footer-count');
- const filter = (document.getElementById('filter-ospf-lsa')?.value || '').toLowerCase();
- let list = state.ospfLSA || [];
- if (filter) {
- list = list.filter(l => (l.type || '').toLowerCase().includes(filter) || (l.originator || '').toLowerCase().includes(filter) || (l.id || '').toLowerCase().includes(filter));
- }
- if (countEl) countEl.innerText = list.length;
- tbody.innerHTML = list.map(l => `
- <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
- <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(l.flags || 'D')}</td>
- <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
- <span class="text-sky-400">↳</span> <span>${escapeHtml(l.instance || 'Default')}</span>
- </td>
- <td class="py-1.5 px-3 text-slate-300">${escapeHtml(l.area || 'Default')}</td>
- <td class="py-1.5 px-3 font-mono text-amber-300">${escapeHtml(l.type || 'router')}</td>
- <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.originator || '')}</td>
- <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(l.id || '')}</td>
- <td class="py-1.5 px-3 text-slate-500">${escapeHtml(l.link || '')}</td>
- <td class="py-1.5 px-3 text-slate-500">${l.link_index ?? 0}</td>
- <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.sequence || '')}</td>
- <td class="py-1.5 px-3 text-slate-400">${l.age ?? 0}</td>
- </tr>
- `).join('');
- }
- function renderOspfStatusPill() {
- // Maintained for backward compatibility
- const pill = document.getElementById('ospf-live-status-pill');
- if (!pill) return;
- 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';
- pill.innerText = 'OSPF ACTIVE';
- }
- function renderOspfInterfaces() {
- renderOspfTemplates();
- }
- function renderOspfRoutes() {
- // Routes retained in background
- }
- // BGP Modals & Actions
- function openBgpInstanceModal() {
- const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
- document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
- document.getElementById('modal-bgp-as').value = inst.as || 65001;
- document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
- document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
- document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
- document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
- document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
- document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
- document.getElementById('bgp-instance-modal').classList.remove('hidden');
- }
- function closeBgpInstanceModal() {
- document.getElementById('bgp-instance-modal').classList.add('hidden');
- }
- async function submitBgpInstance(e) {
- e.preventDefault();
- const payload = {
- enabled: document.getElementById('modal-bgp-enabled').checked,
- as: parseInt(document.getElementById('modal-bgp-as').value, 10),
- router_id: document.getElementById('modal-bgp-router-id').value.trim(),
- keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
- hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
- redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
- redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
- redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
- };
- try {
- const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(payload)
- });
- if (res.ok) {
- closeBgpInstanceModal();
- showToast('Success', 'BGP instance configuration updated', 'success');
- loadDynamicRouting();
- } else {
- const err = await res.json();
- showToast('Error', err.error || 'Failed to update BGP instance', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // ----------------- BGP Peer Connection Modal (DebTik v7) -----------------
- function switchBgpPeerModalTab(tab) {
- // Normalize legacy tab names
- if (tab === 'extra' || tab === 'filter') tab = 'filters';
- if (tab === 'attributes') tab = 'networks';
- const tabs = ['general', 'filters', 'networks'];
- tabs.forEach(t => {
- const pane = document.getElementById(`bgp-peer-tab-${t}`);
- const btn = document.getElementById(`bgp-peer-tab-btn-${t}`);
- if (t === tab) {
- if (pane) pane.classList.remove('hidden');
- if (btn) btn.className = 'px-4 py-2 text-xs font-bold border-b-2 border-cyan-500 text-white transition';
- } else {
- if (pane) pane.classList.add('hidden');
- 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';
- }
- });
- }
- function addOutputNetworkRow(val = '') {
- const container = document.getElementById('modal-bgp-output-networks-container');
- if (!container) return;
- const row = document.createElement('div');
- row.className = 'flex items-center gap-2 output-net-row';
- row.innerHTML = `
- <input type="text" value="${escapeHtml(val)}" placeholder="e.g. 192.168.100.0/24" 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">
- <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>
- `;
- container.appendChild(row);
- }
- function parseBgpTime(val) {
- if (!val) return 0;
- val = String(val).trim();
- if (val.includes(':')) {
- const parts = val.split(':').map(x => parseInt(x, 10) || 0);
- if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2];
- if (parts.length === 2) return parts[0] * 60 + parts[1];
- }
- return parseInt(val, 10) || 0;
- }
- function formatBgpTime(secs) {
- if (!secs || secs <= 0) return '30';
- return String(secs);
- }
- function populateBgpRoutingTables() {
- const sel = document.getElementById('modal-bgp-peer-routing-table');
- if (!sel) return;
- const cur = sel.value || 'main';
- sel.innerHTML = '<option value="main">main</option>';
- (state.routingTables || []).forEach(t => {
- if (t.name !== 'main') {
- const opt = document.createElement('option');
- opt.value = t.name;
- opt.innerText = t.name;
- sel.appendChild(opt);
- }
- });
- sel.value = cur;
- }
- function openAddBgpPeerModal() {
- document.getElementById('bgp-peer-form').reset();
- document.getElementById('modal-bgp-peer-id').value = '';
- document.getElementById('bgp-peer-modal-title').innerText = 'New BGP Connection...';
-
- // General Tab
- document.getElementById('modal-bgp-peer-enabled').checked = true;
- document.getElementById('modal-bgp-peer-name').value = '';
- document.getElementById('modal-bgp-peer-comment').value = '';
- if (document.getElementById('modal-bgp-peer-local-as')) document.getElementById('modal-bgp-peer-local-as').value = '';
- if (document.getElementById('modal-bgp-peer-remote-addr')) document.getElementById('modal-bgp-peer-remote-addr').value = '';
- if (document.getElementById('modal-bgp-peer-remote-port')) document.getElementById('modal-bgp-peer-remote-port').value = '';
- if (document.getElementById('modal-bgp-peer-remote-as')) document.getElementById('modal-bgp-peer-remote-as').value = '';
- if (document.getElementById('modal-bgp-peer-local-addr')) document.getElementById('modal-bgp-peer-local-addr').value = '';
- if (document.getElementById('modal-bgp-peer-local-port')) document.getElementById('modal-bgp-peer-local-port').value = '';
- if (document.getElementById('modal-bgp-peer-local-role')) document.getElementById('modal-bgp-peer-local-role').value = 'ebgp';
- if (document.getElementById('modal-bgp-peer-password')) document.getElementById('modal-bgp-peer-password').value = '';
- if (document.getElementById('modal-bgp-peer-multihop')) document.getElementById('modal-bgp-peer-multihop').checked = false;
- if (document.getElementById('modal-bgp-peer-passive')) document.getElementById('modal-bgp-peer-passive').checked = false;
- if (document.getElementById('modal-bgp-peer-nexthop-self')) document.getElementById('modal-bgp-peer-nexthop-self').checked = false;
- if (document.getElementById('modal-bgp-peer-holdtime')) document.getElementById('modal-bgp-peer-holdtime').value = '30';
- if (document.getElementById('modal-bgp-peer-keepalive')) document.getElementById('modal-bgp-peer-keepalive').value = '10';
- // Filters Tab
- populateFilterChainsDatalist();
- if (document.getElementById('modal-bgp-peer-in-filter')) document.getElementById('modal-bgp-peer-in-filter').value = '';
- if (document.getElementById('modal-bgp-peer-out-filter')) document.getElementById('modal-bgp-peer-out-filter').value = '';
- if (document.getElementById('modal-bgp-peer-redist-conn')) document.getElementById('modal-bgp-peer-redist-conn').checked = false;
- if (document.getElementById('modal-bgp-peer-redist-static')) document.getElementById('modal-bgp-peer-redist-static').checked = true;
- if (document.getElementById('modal-bgp-peer-redist-ospf')) document.getElementById('modal-bgp-peer-redist-ospf').checked = false;
- if (document.getElementById('modal-bgp-peer-default-orig')) document.getElementById('modal-bgp-peer-default-orig').checked = false;
- // Advertised Networks Tab
- const container = document.getElementById('modal-bgp-output-networks-container');
- if (container) {
- container.innerHTML = '';
- addOutputNetworkRow('');
- }
- const removeBtn = document.getElementById('modal-btn-remove-peer');
- if (removeBtn) removeBtn.classList.add('hidden');
- switchBgpPeerModalTab('general');
- document.getElementById('bgp-peer-modal').classList.remove('hidden');
- }
- function populateFilterChainsDatalist() {
- const dl = document.getElementById('filter-chains-list');
- if (!dl) return;
- const chains = new Set();
- (state.routingFilters || []).forEach(f => {
- if (f.chain) chains.add(f.chain);
- });
- if (chains.size === 0) {
- chains.add('awmn');
- chains.add('Internal');
- chains.add('bgp-in');
- chains.add('bgp-out');
- }
- dl.innerHTML = '';
- chains.forEach(c => {
- const opt = document.createElement('option');
- opt.value = c;
- dl.appendChild(opt);
- });
- }
- function openEditBgpPeerModal(id) {
- const p = (state.bgpPeers || []).find(item => item.id === id);
- if (!p) return;
- populateFilterChainsDatalist();
- document.getElementById('modal-bgp-peer-id').value = p.id;
- document.getElementById('bgp-peer-modal-title').innerText = p.name || p.id;
-
- // General Tab
- document.getElementById('modal-bgp-peer-enabled').checked = p.enabled !== false && !p.disabled;
- document.getElementById('modal-bgp-peer-name').value = p.name || '';
- document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
- if (document.getElementById('modal-bgp-peer-local-as')) document.getElementById('modal-bgp-peer-local-as').value = p.local_as || '';
- if (document.getElementById('modal-bgp-peer-remote-addr')) document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
- if (document.getElementById('modal-bgp-peer-remote-port')) document.getElementById('modal-bgp-peer-remote-port').value = p.remote_port || '';
- if (document.getElementById('modal-bgp-peer-remote-as')) document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
- if (document.getElementById('modal-bgp-peer-local-addr')) document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
- if (document.getElementById('modal-bgp-peer-local-port')) document.getElementById('modal-bgp-peer-local-port').value = p.local_port || '';
- if (document.getElementById('modal-bgp-peer-local-role')) document.getElementById('modal-bgp-peer-local-role').value = p.local_role || 'ebgp';
- if (document.getElementById('modal-bgp-peer-password')) document.getElementById('modal-bgp-peer-password').value = p.password || '';
- if (document.getElementById('modal-bgp-peer-multihop')) document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
-
- // Passive mode
- const isPassive = !!p.passive || (p.connect === false && p.listen !== false);
- if (document.getElementById('modal-bgp-peer-passive')) document.getElementById('modal-bgp-peer-passive').checked = isPassive;
- // Next-hop self
- const isNexthopSelf = !!p.nexthop_self || p.nexthop_choice === 'force-self';
- if (document.getElementById('modal-bgp-peer-nexthop-self')) document.getElementById('modal-bgp-peer-nexthop-self').checked = isNexthopSelf;
- if (document.getElementById('modal-bgp-peer-holdtime')) document.getElementById('modal-bgp-peer-holdtime').value = p.hold_time ? String(p.hold_time) : '30';
- if (document.getElementById('modal-bgp-peer-keepalive')) document.getElementById('modal-bgp-peer-keepalive').value = p.keepalive_time ? String(p.keepalive_time) : '10';
- // Filters Tab
- if (document.getElementById('modal-bgp-peer-in-filter')) document.getElementById('modal-bgp-peer-in-filter').value = p.in_filter || '';
- if (document.getElementById('modal-bgp-peer-out-filter')) document.getElementById('modal-bgp-peer-out-filter').value = p.out_filter || '';
- if (document.getElementById('modal-bgp-peer-redist-conn')) document.getElementById('modal-bgp-peer-redist-conn').checked = !!p.redist_connected;
- if (document.getElementById('modal-bgp-peer-redist-static')) document.getElementById('modal-bgp-peer-redist-static').checked = p.redist_static !== false;
- if (document.getElementById('modal-bgp-peer-redist-ospf')) document.getElementById('modal-bgp-peer-redist-ospf').checked = !!p.redist_ospf;
- if (document.getElementById('modal-bgp-peer-default-orig')) document.getElementById('modal-bgp-peer-default-orig').checked = !!p.default_originate;
- // Advertised Networks Tab
- const container = document.getElementById('modal-bgp-output-networks-container');
- if (container) {
- container.innerHTML = '';
- if (p.output_networks && p.output_networks.length > 0) {
- p.output_networks.forEach(net => addOutputNetworkRow(net));
- } else {
- addOutputNetworkRow('');
- }
- }
- const removeBtn = document.getElementById('modal-btn-remove-peer');
- if (removeBtn) removeBtn.classList.remove('hidden');
- switchBgpPeerModalTab('general');
- document.getElementById('bgp-peer-modal').classList.remove('hidden');
- }
- function copyCurrentBgpPeer() {
- document.getElementById('modal-bgp-peer-id').value = '';
- const nameEl = document.getElementById('modal-bgp-peer-name');
- if (nameEl) nameEl.value = (nameEl.value || 'peer') + '-copy';
- document.getElementById('bgp-peer-modal-title').innerText = 'New BGP Connection...';
- const removeBtn = document.getElementById('modal-btn-remove-peer');
- if (removeBtn) removeBtn.classList.add('hidden');
- showToast('Cloned', 'BGP connection copied to new draft', 'info');
- }
- function removeCurrentBgpPeer() {
- const id = document.getElementById('modal-bgp-peer-id')?.value;
- if (!id) return;
- deleteBgpPeer(id);
- closeBgpPeerModal();
- }
- function closeBgpPeerModal() {
- document.getElementById('bgp-peer-modal').classList.add('hidden');
- }
- function getBgpPeerFormData() {
- const netInputs = document.querySelectorAll('#modal-bgp-output-networks-container .output-net-row input');
- const outputNetworks = [];
- netInputs.forEach(inp => {
- const v = inp.value.trim();
- if (v) outputNetworks.push(v);
- });
- const enabled = document.getElementById('modal-bgp-peer-enabled').checked;
- const isPassive = document.getElementById('modal-bgp-peer-passive')?.checked || false;
- const isNexthopSelf = document.getElementById('modal-bgp-peer-nexthop-self')?.checked || false;
- return {
- id: document.getElementById('modal-bgp-peer-id').value,
- name: document.getElementById('modal-bgp-peer-name').value.trim(),
- enabled: enabled,
- disabled: !enabled,
- comment: document.getElementById('modal-bgp-peer-comment').value.trim(),
- local_as: parseInt(document.getElementById('modal-bgp-peer-local-as')?.value, 10) || 0,
- remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
- remote_port: parseInt(document.getElementById('modal-bgp-peer-remote-port').value, 10) || 0,
- remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10) || 0,
- local_address: document.getElementById('modal-bgp-peer-local-addr')?.value.trim() || '',
- local_port: parseInt(document.getElementById('modal-bgp-peer-local-port')?.value, 10) || 0,
- local_role: document.getElementById('modal-bgp-peer-local-role')?.value || 'ebgp',
- password: document.getElementById('modal-bgp-peer-password')?.value || '',
- multihop: document.getElementById('modal-bgp-peer-multihop')?.checked || false,
- passive: isPassive,
- connect: !isPassive,
- listen: true,
- hold_time: parseBgpTime(document.getElementById('modal-bgp-peer-holdtime')?.value),
- keepalive_time: parseBgpTime(document.getElementById('modal-bgp-peer-keepalive')?.value),
- nexthop_self: isNexthopSelf,
- nexthop_choice: isNexthopSelf ? 'force-self' : 'default',
- in_filter: (document.getElementById('modal-bgp-peer-in-filter')?.value || '').trim(),
- out_filter: (document.getElementById('modal-bgp-peer-out-filter')?.value || '').trim(),
- default_originate: document.getElementById('modal-bgp-peer-default-orig')?.checked || false,
- redist_connected: document.getElementById('modal-bgp-peer-redist-conn')?.checked || false,
- redist_static: document.getElementById('modal-bgp-peer-redist-static')?.checked !== false,
- redist_ospf: document.getElementById('modal-bgp-peer-redist-ospf')?.checked || false,
- output_networks: outputNetworks
- };
- }
- async function submitBgpPeer(e) {
- if (e) e.preventDefault();
- const payload = getBgpPeerFormData();
- try {
- const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(payload)
- });
- if (res.ok) {
- closeBgpPeerModal();
- showToast('Success', 'BGP Connection saved', 'success');
- loadDynamicRouting();
- } else {
- const err = await res.json();
- showToast('Error', err.error || 'Failed to save peer', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function applyBgpPeerModal(e) {
- if (e) e.preventDefault();
- const payload = getBgpPeerFormData();
- try {
- const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(payload)
- });
- if (res.ok) {
- const data = await res.json();
- if (data.peer && data.peer.id) {
- document.getElementById('modal-bgp-peer-id').value = data.peer.id;
- document.getElementById('bgp-peer-modal-title').innerText = data.peer.name || data.peer.id;
- document.getElementById('modal-btn-remove-peer')?.classList.remove('hidden');
- }
- showToast('Applied', 'BGP Connection applied', 'success');
- loadDynamicRouting();
- } else {
- const err = await res.json();
- showToast('Error', err.error || 'Failed to apply peer', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deleteBgpPeer(id) {
- if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
- try {
- const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
- if (res.ok) {
- showToast('Deleted', 'BGP peer removed', 'success');
- loadDynamicRouting();
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function toggleBgpPeerState(id, disabled) {
- try {
- const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ disabled })
- });
- if (res.ok) {
- showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
- loadDynamicRouting();
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- function openAddBgpNetworkModal() {
- document.getElementById('bgp-network-form').reset();
- document.getElementById('modal-bgp-net-id').value = '';
- document.getElementById('bgp-network-modal').classList.remove('hidden');
- }
- function closeBgpNetworkModal() {
- document.getElementById('bgp-network-modal').classList.add('hidden');
- }
- async function submitBgpNetwork(e) {
- e.preventDefault();
- const payload = {
- id: document.getElementById('modal-bgp-net-id').value,
- network: document.getElementById('modal-bgp-net-cidr').value.trim(),
- comment: document.getElementById('modal-bgp-net-comment').value.trim(),
- disabled: document.getElementById('modal-bgp-net-disabled').checked
- };
- try {
- const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(payload)
- });
- if (res.ok) {
- closeBgpNetworkModal();
- showToast('Success', 'BGP network advertisement saved', 'success');
- loadDynamicRouting();
- } else {
- const err = await res.json();
- showToast('Error', err.error || 'Failed to save network', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deleteBgpNetwork(id) {
- if (!confirm('Are you sure you want to stop announcing this network?')) return;
- try {
- const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
- if (res.ok) {
- showToast('Deleted', 'Network advertisement removed', 'success');
- loadDynamicRouting();
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // =========================================================================
- // DEBTIK v7 OSPF MODALS & ACTIONS
- // =========================================================================
- // --- 1. OSPF INSTANCE ---
- function openOspfInstanceModal(id = null) {
- const isEdit = !!id;
- const inst = (state.ospfInstances || []).find(i => i.id === id) || {
- id: '',
- name: 'Default',
- version: 2,
- vrf: 'main',
- router_id: '192.168.131.56',
- routing_table: 'main',
- enabled: true,
- redistribute_connected: false,
- redistribute_static: true,
- redistribute_bgp: false,
- comment: ''
- };
- document.getElementById('ospf-instance-modal-title').innerText = isEdit ? inst.name : 'New...';
- document.getElementById('modal-ospf-inst-id').value = isEdit ? inst.id : '';
- document.getElementById('modal-ospf-inst-enabled').checked = !inst.disabled;
- document.getElementById('modal-ospf-inst-comment').value = inst.comment || '';
- document.getElementById('modal-ospf-inst-name').value = inst.name || 'Default';
- document.getElementById('modal-ospf-inst-version').value = inst.version || 2;
- document.getElementById('modal-ospf-inst-vrf').value = inst.vrf || 'main';
- document.getElementById('modal-ospf-inst-router-id').value = inst.router_id || '';
- document.getElementById('modal-ospf-inst-routing-table').value = inst.routing_table || 'main';
- document.getElementById('modal-ospf-inst-redist-conn').checked = !!inst.redistribute_connected;
- document.getElementById('modal-ospf-inst-redist-static').checked = inst.redistribute_static !== false;
- document.getElementById('modal-ospf-inst-redist-bgp').checked = !!inst.redistribute_bgp;
- const btnRem = document.getElementById('btn-ospf-inst-modal-remove');
- if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
- document.getElementById('ospf-instance-modal').classList.remove('hidden');
- }
- function openEditOspfInstanceModal(id) {
- openOspfInstanceModal(id);
- }
- function closeOspfInstanceModal() {
- document.getElementById('ospf-instance-modal').classList.add('hidden');
- }
- async function submitOspfInstance(e) {
- if (e) e.preventDefault();
- const payload = {
- id: document.getElementById('modal-ospf-inst-id').value,
- name: document.getElementById('modal-ospf-inst-name').value.trim() || 'Default',
- version: parseInt(document.getElementById('modal-ospf-inst-version').value, 10) || 2,
- vrf: document.getElementById('modal-ospf-inst-vrf').value.trim() || 'main',
- router_id: document.getElementById('modal-ospf-inst-router-id').value.trim(),
- routing_table: document.getElementById('modal-ospf-inst-routing-table').value.trim() || 'main',
- enabled: document.getElementById('modal-ospf-inst-enabled').checked,
- disabled: !document.getElementById('modal-ospf-inst-enabled').checked,
- comment: document.getElementById('modal-ospf-inst-comment').value.trim(),
- redistribute_connected: document.getElementById('modal-ospf-inst-redist-conn').checked,
- redistribute_static: document.getElementById('modal-ospf-inst-redist-static').checked,
- redistribute_bgp: document.getElementById('modal-ospf-inst-redist-bgp').checked
- };
- try {
- const res = await fetch(`${API_BASE}/routing/ospf/instances`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(payload)
- });
- if (res.ok) {
- closeOspfInstanceModal();
- showToast('Saved', 'OSPF instance updated', 'success');
- loadDynamicRouting();
- } else {
- const err = await res.json();
- showToast('Error', err.error || 'Failed to save OSPF instance', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- function applyOspfInstanceForm() {
- submitOspfInstance(null);
- }
- function copyOspfInstance() {
- document.getElementById('modal-ospf-inst-id').value = '';
- document.getElementById('modal-ospf-inst-name').value += '-copy';
- document.getElementById('ospf-instance-modal-title').innerText = 'New...';
- showToast('Copied', 'Duplicated as new OSPF instance', 'info');
- }
- async function deleteCurrentOspfInstance() {
- const id = document.getElementById('modal-ospf-inst-id').value;
- if (!id) return;
- if (!confirm('Are you sure you want to remove this OSPF instance?')) return;
- try {
- const res = await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
- if (res.ok) {
- closeOspfInstanceModal();
- showToast('Removed', 'OSPF instance deleted', 'success');
- loadDynamicRouting();
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function enableSelectedOspfInstance() {
- const id = state.selectedOspfRow?.instances;
- if (!id) return;
- await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ disabled: false })
- });
- loadDynamicRouting();
- }
- async function disableSelectedOspfInstance() {
- const id = state.selectedOspfRow?.instances;
- if (!id) return;
- await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ disabled: true })
- });
- loadDynamicRouting();
- }
- async function removeSelectedOspfInstance() {
- const id = state.selectedOspfRow?.instances;
- if (!id) return;
- if (!confirm('Delete selected OSPF instance?')) return;
- await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
- loadDynamicRouting();
- }
- async function promptCommentOspfInstance() {
- const id = state.selectedOspfRow?.instances;
- if (!id) return;
- const inst = (state.ospfInstances || []).find(i => i.id === id);
- if (!inst) return;
- const comment = prompt('Enter comment for OSPF instance:', inst.comment || '');
- if (comment === null) return;
- inst.comment = comment;
- await fetch(`${API_BASE}/routing/ospf/instances`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(inst)
- });
- loadDynamicRouting();
- }
- // --- 2. OSPF AREA ---
- function populateOspfAreaDropdowns() {
- const instSelect = document.getElementById('modal-ospf-area-instance');
- if (instSelect) {
- const cur = instSelect.value;
- instSelect.innerHTML = (state.ospfInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
- if (instSelect.innerHTML === '') instSelect.innerHTML = '<option value="Default">Default</option>';
- if (cur) instSelect.value = cur;
- }
- }
- function openOspfAreaModal(id = null) {
- const isEdit = !!id;
- populateOspfAreaDropdowns();
- const area = (state.ospfAreas || []).find(a => a.id === id) || {
- id: '',
- name: 'Default',
- instance: 'Default',
- area_id: '0.0.0.0',
- area_type: 'default',
- default_cost: 1,
- no_summaries: false,
- disabled: false,
- comment: ''
- };
- document.getElementById('ospf-area-modal-title').innerText = isEdit ? area.name : 'New...';
- document.getElementById('modal-ospf-area-id').value = isEdit ? area.id : '';
- document.getElementById('modal-ospf-area-enabled').checked = !area.disabled;
- document.getElementById('modal-ospf-area-comment').value = area.comment || '';
- document.getElementById('modal-ospf-area-name').value = area.name || 'Default';
- document.getElementById('modal-ospf-area-instance').value = area.instance || 'Default';
- document.getElementById('modal-ospf-area-areaid').value = area.area_id || '0.0.0.0';
- document.getElementById('modal-ospf-area-type').value = area.area_type || 'default';
- document.getElementById('modal-ospf-area-default-cost').value = area.default_cost || 1;
- document.getElementById('modal-ospf-area-no-summaries').checked = !!area.no_summaries;
- const btnRem = document.getElementById('btn-ospf-area-modal-remove');
- if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
- document.getElementById('ospf-area-modal').classList.remove('hidden');
- }
- function openEditOspfAreaModal(id) {
- openOspfAreaModal(id);
- }
- function closeOspfAreaModal() {
- document.getElementById('ospf-area-modal').classList.add('hidden');
- }
- async function submitOspfArea(e) {
- if (e) e.preventDefault();
- const payload = {
- id: document.getElementById('modal-ospf-area-id').value,
- name: document.getElementById('modal-ospf-area-name').value.trim() || 'Default',
- instance: document.getElementById('modal-ospf-area-instance').value.trim() || 'Default',
- area_id: document.getElementById('modal-ospf-area-areaid').value.trim() || '0.0.0.0',
- area_type: document.getElementById('modal-ospf-area-type').value,
- default_cost: parseInt(document.getElementById('modal-ospf-area-default-cost').value, 10) || 1,
- no_summaries: document.getElementById('modal-ospf-area-no-summaries').checked,
- disabled: !document.getElementById('modal-ospf-area-enabled').checked,
- comment: document.getElementById('modal-ospf-area-comment').value.trim()
- };
- try {
- const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(payload)
- });
- if (res.ok) {
- closeOspfAreaModal();
- showToast('Saved', 'OSPF area saved', 'success');
- loadDynamicRouting();
- } else {
- const err = await res.json();
- showToast('Error', err.error || 'Failed to save area', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- function applyOspfAreaForm() {
- submitOspfArea(null);
- }
- function copyOspfArea() {
- document.getElementById('modal-ospf-area-id').value = '';
- document.getElementById('modal-ospf-area-name').value += '-copy';
- document.getElementById('ospf-area-modal-title').innerText = 'New...';
- showToast('Copied', 'Duplicated as new OSPF area', 'info');
- }
- async function deleteCurrentOspfArea() {
- const id = document.getElementById('modal-ospf-area-id').value;
- if (!id) return;
- if (!confirm('Are you sure you want to remove this OSPF area?')) return;
- try {
- const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
- if (res.ok) {
- closeOspfAreaModal();
- showToast('Removed', 'OSPF area deleted', 'success');
- loadDynamicRouting();
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function enableSelectedOspfArea() {
- const id = state.selectedOspfRow?.areas;
- if (!id) return;
- await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ disabled: false })
- });
- loadDynamicRouting();
- }
- async function disableSelectedOspfArea() {
- const id = state.selectedOspfRow?.areas;
- if (!id) return;
- await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ disabled: true })
- });
- loadDynamicRouting();
- }
- async function removeSelectedOspfArea() {
- const id = state.selectedOspfRow?.areas;
- if (!id) return;
- if (!confirm('Delete selected OSPF area?')) return;
- await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
- loadDynamicRouting();
- }
- async function promptCommentOspfArea() {
- const id = state.selectedOspfRow?.areas;
- if (!id) return;
- const area = (state.ospfAreas || []).find(a => a.id === id);
- if (!area) return;
- const comment = prompt('Enter comment for OSPF area:', area.comment || '');
- if (comment === null) return;
- area.comment = comment;
- await fetch(`${API_BASE}/routing/ospf/areas`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(area)
- });
- loadDynamicRouting();
- }
- // --- 3. OSPF AREA RANGE ---
- function populateAreaRangeDropdowns() {
- const select = document.getElementById('modal-ospf-range-area');
- if (select) {
- const cur = select.value;
- select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
- if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
- if (cur) select.value = cur;
- }
- }
- function openOspfAreaRangeModal(id = null) {
- const isEdit = !!id;
- populateAreaRangeDropdowns();
- const r = (state.ospfAreaRanges || []).find(it => it.id === id) || {
- id: '',
- area: 'Default',
- prefix: '',
- cost: 1,
- advertise: true,
- disabled: false,
- comment: ''
- };
- document.getElementById('ospf-area-range-modal-title').innerText = isEdit ? r.prefix : 'New...';
- document.getElementById('modal-ospf-range-id').value = isEdit ? r.id : '';
- document.getElementById('modal-ospf-range-enabled').checked = !r.disabled;
- document.getElementById('modal-ospf-range-comment').value = r.comment || '';
- document.getElementById('modal-ospf-range-area').value = r.area || 'Default';
- document.getElementById('modal-ospf-range-prefix').value = r.prefix || '';
- document.getElementById('modal-ospf-range-cost').value = r.cost || 1;
- document.getElementById('modal-ospf-range-advertise').checked = r.advertise !== false;
- const btnRem = document.getElementById('btn-ospf-range-modal-remove');
- if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
- document.getElementById('ospf-area-range-modal').classList.remove('hidden');
- }
- function openEditOspfAreaRangeModal(id) {
- openOspfAreaRangeModal(id);
- }
- function closeOspfAreaRangeModal() {
- document.getElementById('ospf-area-range-modal').classList.add('hidden');
- }
- async function submitOspfAreaRange(e) {
- if (e) e.preventDefault();
- const payload = {
- id: document.getElementById('modal-ospf-range-id').value,
- area: document.getElementById('modal-ospf-range-area').value,
- prefix: document.getElementById('modal-ospf-range-prefix').value.trim(),
- cost: parseInt(document.getElementById('modal-ospf-range-cost').value, 10) || 1,
- advertise: document.getElementById('modal-ospf-range-advertise').checked,
- disabled: !document.getElementById('modal-ospf-range-enabled').checked,
- comment: document.getElementById('modal-ospf-range-comment').value.trim()
- };
- try {
- const res = await fetch(`${API_BASE}/routing/ospf/area-ranges`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(payload)
- });
- if (res.ok) {
- closeOspfAreaRangeModal();
- showToast('Saved', 'Area range saved', 'success');
- loadDynamicRouting();
- } else {
- const err = await res.json();
- showToast('Error', err.error || 'Failed to save area range', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- function applyOspfAreaRangeForm() {
- submitOspfAreaRange(null);
- }
- async function deleteCurrentOspfAreaRange() {
- const id = document.getElementById('modal-ospf-range-id').value;
- if (!id) return;
- if (!confirm('Delete this area range?')) return;
- try {
- await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
- closeOspfAreaRangeModal();
- showToast('Removed', 'Area range removed', 'success');
- loadDynamicRouting();
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function enableSelectedOspfAreaRange() {
- const id = state.selectedOspfRow?.['area-ranges'];
- if (!id) return;
- const r = (state.ospfAreaRanges || []).find(it => it.id === id);
- if (!r) return;
- r.disabled = false;
- await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
- loadDynamicRouting();
- }
- async function disableSelectedOspfAreaRange() {
- const id = state.selectedOspfRow?.['area-ranges'];
- if (!id) return;
- const r = (state.ospfAreaRanges || []).find(it => it.id === id);
- if (!r) return;
- r.disabled = true;
- await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
- loadDynamicRouting();
- }
- async function removeSelectedOspfAreaRange() {
- const id = state.selectedOspfRow?.['area-ranges'];
- if (!id) return;
- if (!confirm('Delete selected area range?')) return;
- await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
- loadDynamicRouting();
- }
- async function promptCommentOspfAreaRange() {
- const id = state.selectedOspfRow?.['area-ranges'];
- if (!id) return;
- const r = (state.ospfAreaRanges || []).find(it => it.id === id);
- if (!r) return;
- const comment = prompt('Enter comment for area range:', r.comment || '');
- if (comment === null) return;
- r.comment = comment;
- await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
- loadDynamicRouting();
- }
- // --- 4. OSPF INTERFACE TEMPLATE ---
- function switchOspfTemplateTab(tab) {
- const tabGen = document.getElementById('ospf-tmpl-tab-general');
- const tabAuth = document.getElementById('ospf-tmpl-tab-auth');
- const btnGen = document.getElementById('ospf-tmpl-tab-btn-general');
- const btnAuth = document.getElementById('ospf-tmpl-tab-btn-auth');
- if (tab === 'general') {
- if (tabGen) tabGen.classList.remove('hidden');
- if (tabAuth) tabAuth.classList.add('hidden');
- if (btnGen) btnGen.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
- 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';
- } else {
- if (tabGen) tabGen.classList.add('hidden');
- if (tabAuth) tabAuth.classList.remove('hidden');
- 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';
- if (btnAuth) btnAuth.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
- }
- }
- function populateTemplateAreaDropdowns() {
- const select = document.getElementById('modal-ospf-tmpl-area');
- if (select) {
- const cur = select.value;
- select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
- if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
- if (cur) select.value = cur;
- }
- }
- function openOspfTemplateModal(id = null) {
- const isEdit = !!id;
- populateTemplateAreaDropdowns();
- switchOspfTemplateTab('general');
- const tmpl = (state.ospfTemplates || []).find(t => t.id === id) || {
- id: '',
- interfaces: '',
- area: 'Default',
- networks: '',
- network_type: 'broadcast',
- cost: 1,
- priority: 128,
- passive: false,
- hello_interval: 10,
- dead_interval: 40,
- auth: 'none',
- auth_key: '',
- disabled: false,
- comment: ''
- };
- document.getElementById('ospf-template-modal-title').innerText = isEdit ? (tmpl.interfaces || tmpl.networks || 'Template') : 'New...';
- document.getElementById('modal-ospf-tmpl-id').value = isEdit ? tmpl.id : '';
- document.getElementById('modal-ospf-tmpl-enabled').checked = !tmpl.disabled;
- document.getElementById('modal-ospf-tmpl-comment').value = tmpl.comment || '';
- document.getElementById('modal-ospf-tmpl-interfaces').value = tmpl.interfaces || tmpl.interface || '';
- document.getElementById('modal-ospf-tmpl-area').value = tmpl.area || 'Default';
- document.getElementById('modal-ospf-tmpl-networks').value = tmpl.networks || tmpl.network || '';
- document.getElementById('modal-ospf-tmpl-net-type').value = tmpl.network_type || 'broadcast';
- document.getElementById('modal-ospf-tmpl-cost').value = tmpl.cost || 1;
- document.getElementById('modal-ospf-tmpl-priority').value = tmpl.priority || 128;
- document.getElementById('modal-ospf-tmpl-passive').checked = !!tmpl.passive;
- document.getElementById('modal-ospf-tmpl-hello').value = tmpl.hello_interval || 10;
- document.getElementById('modal-ospf-tmpl-dead').value = tmpl.dead_interval || 40;
- document.getElementById('modal-ospf-tmpl-auth').value = tmpl.auth || tmpl.auth_type || 'none';
- document.getElementById('modal-ospf-tmpl-auth-key').value = tmpl.auth_key || '';
- const btnRem = document.getElementById('btn-ospf-tmpl-modal-remove');
- if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
- document.getElementById('ospf-template-modal').classList.remove('hidden');
- }
- function openEditOspfTemplateModal(id) {
- openOspfTemplateModal(id);
- }
- function closeOspfTemplateModal() {
- document.getElementById('ospf-template-modal').classList.add('hidden');
- }
- async function submitOspfTemplate(e) {
- if (e) e.preventDefault();
- const payload = {
- id: document.getElementById('modal-ospf-tmpl-id').value,
- interfaces: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
- interface: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
- area: document.getElementById('modal-ospf-tmpl-area').value,
- networks: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
- network: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
- network_type: document.getElementById('modal-ospf-tmpl-net-type').value,
- cost: parseInt(document.getElementById('modal-ospf-tmpl-cost').value, 10) || 1,
- priority: parseInt(document.getElementById('modal-ospf-tmpl-priority').value, 10) || 128,
- passive: document.getElementById('modal-ospf-tmpl-passive').checked,
- hello_interval: parseInt(document.getElementById('modal-ospf-tmpl-hello').value, 10) || 10,
- dead_interval: parseInt(document.getElementById('modal-ospf-tmpl-dead').value, 10) || 40,
- auth: document.getElementById('modal-ospf-tmpl-auth').value,
- auth_type: document.getElementById('modal-ospf-tmpl-auth').value,
- auth_key: document.getElementById('modal-ospf-tmpl-auth-key').value,
- disabled: !document.getElementById('modal-ospf-tmpl-enabled').checked,
- comment: document.getElementById('modal-ospf-tmpl-comment').value.trim()
- };
- try {
- const res = await fetch(`${API_BASE}/routing/ospf/templates`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(payload)
- });
- if (res.ok) {
- closeOspfTemplateModal();
- showToast('Saved', 'Interface template saved', 'success');
- loadDynamicRouting();
- } else {
- const err = await res.json();
- showToast('Error', err.error || 'Failed to save interface template', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- function applyOspfTemplateForm() {
- submitOspfTemplate(null);
- }
- function copyOspfTemplate() {
- document.getElementById('modal-ospf-tmpl-id').value = '';
- document.getElementById('ospf-template-modal-title').innerText = 'New...';
- showToast('Copied', 'Duplicated as new template', 'info');
- }
- async function deleteCurrentOspfTemplate() {
- const id = document.getElementById('modal-ospf-tmpl-id').value;
- if (!id) return;
- if (!confirm('Delete this interface template?')) return;
- try {
- await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
- closeOspfTemplateModal();
- showToast('Removed', 'Interface template deleted', 'success');
- loadDynamicRouting();
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function enableSelectedOspfTemplate() {
- const id = state.selectedOspfRow?.templates;
- if (!id) return;
- await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ disabled: false })
- });
- loadDynamicRouting();
- }
- async function disableSelectedOspfTemplate() {
- const id = state.selectedOspfRow?.templates;
- if (!id) return;
- await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ disabled: true })
- });
- loadDynamicRouting();
- }
- async function removeSelectedOspfTemplate() {
- const id = state.selectedOspfRow?.templates;
- if (!id) return;
- if (!confirm('Delete selected interface template?')) return;
- await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
- loadDynamicRouting();
- }
- async function promptCommentOspfTemplate() {
- const id = state.selectedOspfRow?.templates;
- if (!id) return;
- const tmpl = (state.ospfTemplates || []).find(t => t.id === id);
- if (!tmpl) return;
- const comment = prompt('Enter comment for template:', tmpl.comment || '');
- if (comment === null) return;
- tmpl.comment = comment;
- await fetch(`${API_BASE}/routing/ospf/templates`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(tmpl)
- });
- loadDynamicRouting();
- }
- // --- 5. OSPF STATIC NEIGHBOR ---
- function populateStaticNbrAreaDropdowns() {
- const select = document.getElementById('modal-ospf-snbr-area');
- if (select) {
- const cur = select.value;
- select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
- if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
- if (cur) select.value = cur;
- }
- }
- function openOspfStaticNbrModal(id = null) {
- const isEdit = !!id;
- populateStaticNbrAreaDropdowns();
- const nbr = (state.ospfStaticNbrs || []).find(n => n.id === id) || {
- id: '',
- address: '',
- area: 'Default',
- poll_interval: 120,
- cost: 1,
- disabled: false,
- comment: ''
- };
- document.getElementById('ospf-static-nbr-modal-title').innerText = isEdit ? nbr.address : 'New...';
- document.getElementById('modal-ospf-snbr-id').value = isEdit ? nbr.id : '';
- document.getElementById('modal-ospf-snbr-enabled').checked = !nbr.disabled;
- document.getElementById('modal-ospf-snbr-comment').value = nbr.comment || '';
- document.getElementById('modal-ospf-snbr-address').value = nbr.address || '';
- document.getElementById('modal-ospf-snbr-area').value = nbr.area || 'Default';
- document.getElementById('modal-ospf-snbr-poll').value = nbr.poll_interval || 120;
- document.getElementById('modal-ospf-snbr-cost').value = nbr.cost || 1;
- const btnRem = document.getElementById('btn-ospf-snbr-modal-remove');
- if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
- document.getElementById('ospf-static-nbr-modal').classList.remove('hidden');
- }
- function openEditOspfStaticNbrModal(id) {
- openOspfStaticNbrModal(id);
- }
- function closeOspfStaticNbrModal() {
- document.getElementById('ospf-static-nbr-modal').classList.add('hidden');
- }
- async function submitOspfStaticNbr(e) {
- if (e) e.preventDefault();
- const payload = {
- id: document.getElementById('modal-ospf-snbr-id').value,
- address: document.getElementById('modal-ospf-snbr-address').value.trim(),
- area: document.getElementById('modal-ospf-snbr-area').value,
- poll_interval: parseInt(document.getElementById('modal-ospf-snbr-poll').value, 10) || 120,
- cost: parseInt(document.getElementById('modal-ospf-snbr-cost').value, 10) || 1,
- disabled: !document.getElementById('modal-ospf-snbr-enabled').checked,
- comment: document.getElementById('modal-ospf-snbr-comment').value.trim()
- };
- try {
- const res = await fetch(`${API_BASE}/routing/ospf/static-neighbors`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(payload)
- });
- if (res.ok) {
- closeOspfStaticNbrModal();
- showToast('Saved', 'Static neighbor saved', 'success');
- loadDynamicRouting();
- } else {
- const err = await res.json();
- showToast('Error', err.error || 'Failed to save static neighbor', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- function applyOspfStaticNbrForm() {
- submitOspfStaticNbr(null);
- }
- async function deleteCurrentOspfStaticNbr() {
- const id = document.getElementById('modal-ospf-snbr-id').value;
- if (!id) return;
- if (!confirm('Delete this static neighbor?')) return;
- try {
- await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
- closeOspfStaticNbrModal();
- showToast('Removed', 'Static neighbor removed', 'success');
- loadDynamicRouting();
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function enableSelectedOspfStaticNbr() {
- const id = state.selectedOspfRow?.['static-nbrs'];
- if (!id) return;
- await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
- loadDynamicRouting();
- }
- async function disableSelectedOspfStaticNbr() {
- const id = state.selectedOspfRow?.['static-nbrs'];
- if (!id) return;
- await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
- loadDynamicRouting();
- }
- async function removeSelectedOspfStaticNbr() {
- const id = state.selectedOspfRow?.['static-nbrs'];
- if (!id) return;
- if (!confirm('Delete selected static neighbor?')) return;
- await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
- loadDynamicRouting();
- }
- async function promptCommentOspfStaticNbr() {
- const id = state.selectedOspfRow?.['static-nbrs'];
- if (!id) return;
- const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
- if (!n) return;
- const comment = prompt('Enter comment for static neighbor:', n.comment || '');
- if (comment === null) return;
- n.comment = comment;
- await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
- loadDynamicRouting();
- }
- // Backward-compat aliases
- function openAddOspfInterfaceModal() { openOspfTemplateModal(); }
- function openEditOspfInterfaceModal(id) { openEditOspfTemplateModal(id); }
- function closeOspfInterfaceModal() { closeOspfTemplateModal(); }
- function submitOspfInterface(e) { submitOspfTemplate(e); }
- function deleteOspfInterface(id) {
- fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
- }
- function toggleOspfInterfaceState(id, disabled) {
- fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ disabled })
- }).then(() => loadDynamicRouting());
- }
- function openAddOspfAreaModal() { openOspfAreaModal(); }
- function deleteOspfArea(id) {
- fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
- }
- // ============================================================================
- // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
- // ============================================================================
- function switchBridgeSubTab(tab) {
- state.bridgeSubTab = tab;
- const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
- tabs.forEach(t => {
- const panel = document.getElementById(`bridge-subtab-${t}`);
- const btn = document.getElementById(`bridge-subtab-btn-${t}`);
- if (panel) {
- if (t === tab) panel.classList.remove('hidden');
- else panel.classList.add('hidden');
- }
- if (btn) {
- if (t === tab) {
- 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';
- } else {
- 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';
- }
- }
- });
- const addBtn = document.getElementById('bridge-top-action-btn');
- if (addBtn) {
- if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
- else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
- else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
- else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
- }
- if (tab === 'hosts') loadBridgeHosts();
- setTimeout(initTableSorting, 50);
- }
- function openCurrentBridgeModal() {
- if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
- else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
- else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
- else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
- }
- async function loadBridge() {
- try {
- const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vxlanRes, vlanIfacesRes] = await Promise.all([
- fetch(`${API_BASE}/bridge/bridges`),
- fetch(`${API_BASE}/bridge/ports`),
- fetch(`${API_BASE}/bridge/vlans`),
- fetch(`${API_BASE}/bridge/summary`),
- fetch(`${API_BASE}/vpn/eoip`),
- fetch(`${API_BASE}/vpn/vxlan`),
- fetch(`${API_BASE}/vlans`)
- ]);
- if (bridgesRes.ok) state.bridges = await bridgesRes.json();
- if (portsRes.ok) state.bridgePorts = await portsRes.json();
- if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
- if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
- if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
- if (vxlanRes && vxlanRes.ok) state.vxlanTunnels = await vxlanRes.json();
- if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
- // Badges & Stats
- const bBridges = document.getElementById('bridge-badge-bridges');
- if (bBridges) bBridges.innerText = (state.bridges || []).length;
- const bPorts = document.getElementById('bridge-badge-ports');
- if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
- const bVlans = document.getElementById('bridge-badge-vlans');
- if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
- const bHosts = document.getElementById('bridge-badge-hosts');
- if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
- const sBr = document.getElementById('bridge-stat-bridges');
- if (sBr) sBr.innerText = (state.bridges || []).length;
- const sPorts = document.getElementById('bridge-stat-ports');
- if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
- const sHosts = document.getElementById('bridge-stat-hosts');
- if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
- renderBridges();
- renderBridgePorts();
- renderBridgeVLANs();
- if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
- } catch (err) {
- console.error('Failed to load bridge subsystem:', err);
- }
- }
- // ----------------- Bridges -----------------
- function renderBridges() {
- const tbody = document.getElementById('bridge-table-body');
- const empty = document.getElementById('bridge-empty-bridges');
- const countBadge = document.getElementById('bridge-count-badge');
- if (!tbody) return;
- tbody.innerHTML = '';
- const bridges = state.bridges || [];
- if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
- if (bridges.length === 0) {
- empty?.classList.remove('hidden');
- return;
- }
- empty?.classList.add('hidden');
- bridges.forEach((b, idx) => {
- const tr = document.createElement('tr');
- tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
- // Format IP addresses pill list
- let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
- if (b.ip_addresses && b.ip_addresses.length > 0) {
- ipsHtml = b.ip_addresses.map(ip => `
- <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">
- <span>${ip}</span>
- <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
- </span>
- `).join(' ');
- }
- const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
- const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
- const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
- tr.innerHTML = `
- <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
- <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
- <td class="py-2.5 px-3 font-bold text-white text-sm">
- <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
- </td>
- <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
- <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
- <td class="py-2.5 px-3">
- <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>
- </td>
- <td class="py-2.5 px-3 text-center">
- ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
- </td>
- <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
- <td class="py-2.5 px-3">
- <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>
- </td>
- <td class="py-2.5 px-3">
- <div class="flex items-center gap-1.5 flex-wrap">
- ${ipsHtml}
- <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>
- </div>
- </td>
- <td class="py-2.5 px-3 text-[11px] text-slate-400">
- <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
- </td>
- <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
- <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
- <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>
- <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
- <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
- </td>
- `;
- tbody.appendChild(tr);
- });
- }
- function openAddBridgeModal() {
- document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
- document.getElementById('bridge-modal-id').value = '';
- document.getElementById('bridge-modal-name').value = 'bridge1';
- document.getElementById('bridge-modal-name').disabled = false;
- document.getElementById('bridge-modal-mtu').value = '1500';
- document.getElementById('bridge-modal-mac').value = '';
- document.getElementById('bridge-modal-stp').value = 'stp';
- document.getElementById('bridge-modal-priority').value = '32768';
- document.getElementById('bridge-modal-vlanfiltering').checked = false;
- document.getElementById('bridge-modal-pvid').value = '1';
- document.getElementById('bridge-modal-fastforward').checked = true;
- document.getElementById('bridge-modal-comment').value = '';
- document.getElementById('bridge-modal-disabled').checked = false;
- toggleBridgeModalVlanFiltering();
- document.getElementById('bridge-modal').classList.remove('hidden');
- }
- function openEditBridgeModal(id) {
- const b = (state.bridges || []).find(x => x.id === id);
- if (!b) return;
- document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
- document.getElementById('bridge-modal-id').value = b.id;
- document.getElementById('bridge-modal-name').value = b.name;
- document.getElementById('bridge-modal-name').disabled = true;
- document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
- document.getElementById('bridge-modal-mac').value = b.mac_address || '';
- document.getElementById('bridge-modal-stp').value = b.stp || 'stp';
- document.getElementById('bridge-modal-priority').value = b.priority || 32768;
- document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
- document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
- document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
- document.getElementById('bridge-modal-comment').value = b.comment || '';
- document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
- toggleBridgeModalVlanFiltering();
- document.getElementById('bridge-modal').classList.remove('hidden');
- }
- function closeBridgeModal() {
- document.getElementById('bridge-modal').classList.add('hidden');
- }
- function toggleBridgeModalVlanFiltering() {
- const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
- const pvidBox = document.getElementById('bridge-modal-pvid-box');
- if (pvidBox) {
- if (chk) pvidBox.classList.remove('opacity-40');
- else pvidBox.classList.add('opacity-40');
- }
- }
- async function submitSaveBridge(e) {
- e.preventDefault();
- const id = document.getElementById('bridge-modal-id').value;
- const name = document.getElementById('bridge-modal-name').value.trim();
- const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
- const mac = document.getElementById('bridge-modal-mac').value.trim();
- const stp = document.getElementById('bridge-modal-stp').value;
- const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
- const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
- const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
- const fastForward = document.getElementById('bridge-modal-fastforward').checked;
- const comment = document.getElementById('bridge-modal-comment').value.trim();
- const disabled = document.getElementById('bridge-modal-disabled').checked;
- try {
- const res = await fetch(`${API_BASE}/bridge/bridges`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- id,
- name,
- mtu,
- mac_address: mac,
- stp,
- priority,
- vlan_filtering: vlanFiltering,
- pvid,
- fast_forward: fastForward,
- comment,
- disabled
- })
- });
- if (res.ok) {
- showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
- closeBridgeModal();
- loadBridge();
- fetchData(false);
- } else {
- const err = await res.json();
- showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function toggleBridgeState(id, disabled) {
- try {
- const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ disabled })
- });
- if (res.ok) {
- loadBridge();
- fetchData(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deleteBridge(id) {
- const b = (state.bridges || []).find(x => x.id === id);
- const name = b ? b.name : id;
- if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
- try {
- const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
- if (res.ok) {
- showToast('Deleted', `Bridge ${name} deleted`, 'success');
- loadBridge();
- fetchData(false);
- } else {
- const err = await res.json();
- showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // ----------------- Bridge IP Assignments -----------------
- function openAddBridgeIPModal(id, name) {
- document.getElementById('bridge-ip-modal-id').value = id;
- document.getElementById('bridge-ip-modal-sub').innerText = name;
- document.getElementById('bridge-ip-modal-cidr').value = '';
- document.getElementById('bridge-ip-modal').classList.remove('hidden');
- }
- function closeBridgeIPModal() {
- document.getElementById('bridge-ip-modal').classList.add('hidden');
- }
- async function submitAddBridgeIP(e) {
- e.preventDefault();
- const id = document.getElementById('bridge-ip-modal-id').value;
- const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
- try {
- const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ ip })
- });
- if (res.ok) {
- showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
- closeBridgeIPModal();
- loadBridge();
- fetchData(false);
- } else {
- const err = await res.json();
- showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deleteBridgeIP(id, ip) {
- if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
- try {
- const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
- method: 'DELETE',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ ip })
- });
- if (res.ok) {
- showToast('IP Removed', `${ip} removed from bridge`, 'success');
- loadBridge();
- fetchData(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // ----------------- Bridge Ports -----------------
- function renderBridgePorts() {
- const tbody = document.getElementById('bridge-ports-table-body');
- const empty = document.getElementById('bridge-empty-ports');
- const countBadge = document.getElementById('bridge-ports-count-badge');
- const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
- if (!tbody) return;
- tbody.innerHTML = '';
- // Update filter select
- populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
- const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
- if (countBadge) countBadge.innerText = `${ports.length} Ports`;
- if (ports.length === 0) {
- empty?.classList.remove('hidden');
- return;
- }
- empty?.classList.add('hidden');
- ports.forEach((p, idx) => {
- const tr = document.createElement('tr');
- tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
- const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
- tr.innerHTML = `
- <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
- <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
- <td class="py-2.5 px-3 font-bold text-white text-sm">
- <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
- </td>
- <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
- <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
- <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
- <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>
- <td class="py-2.5 px-3">
- ${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>'}
- </td>
- <td class="py-2.5 px-3">
- <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>
- </td>
- <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
- <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
- <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>
- <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
- <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
- </td>
- `;
- tbody.appendChild(tr);
- });
- }
- function openAddBridgePortModal() {
- document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
- document.getElementById('bridge-port-modal-id').value = '';
- populateBridgeSelect('bridge-port-modal-bridge');
- populateBridgePortCandidateSelect('bridge-port-modal-interface');
- document.getElementById('bridge-port-modal-pvid').value = '1';
- document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
- document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
- document.getElementById('bridge-port-modal-horizon').value = '0';
- document.getElementById('bridge-port-modal-pathcost').value = '10';
- document.getElementById('bridge-port-modal-priority').value = '128';
- document.getElementById('bridge-port-modal-learn').checked = true;
- document.getElementById('bridge-port-modal-comment').value = '';
- document.getElementById('bridge-port-modal-disabled').checked = false;
- document.getElementById('bridge-port-modal').classList.remove('hidden');
- }
- function openEditBridgePortModal(id) {
- const p = (state.bridgePorts || []).find(x => x.id === id);
- if (!p) return;
- document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
- document.getElementById('bridge-port-modal-id').value = p.id;
- populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
- populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
- document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
- document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
- document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
- document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
- document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
- document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
- document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
- document.getElementById('bridge-port-modal-comment').value = p.comment || '';
- document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
- document.getElementById('bridge-port-modal').classList.remove('hidden');
- }
- function closeBridgePortModal() {
- document.getElementById('bridge-port-modal').classList.add('hidden');
- }
- async function submitSaveBridgePort(e) {
- e.preventDefault();
- const id = document.getElementById('bridge-port-modal-id').value;
- const bridge = document.getElementById('bridge-port-modal-bridge').value;
- const iface = document.getElementById('bridge-port-modal-interface').value;
- const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
- const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
- const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
- const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
- const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
- const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
- const learn = document.getElementById('bridge-port-modal-learn').checked;
- const comment = document.getElementById('bridge-port-modal-comment').value.trim();
- const disabled = document.getElementById('bridge-port-modal-disabled').checked;
- try {
- const res = await fetch(`${API_BASE}/bridge/ports`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- id,
- bridge,
- interface: iface,
- pvid,
- frame_types: frameTypes,
- ingress_filtering: ingressFiltering,
- horizon,
- path_cost: pathCost,
- priority,
- learn,
- comment,
- disabled
- })
- });
- if (res.ok) {
- showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
- closeBridgePortModal();
- loadBridge();
- fetchData(false);
- } else {
- const err = await res.json();
- showToast('Error', err.error || err.message || 'Failed to save port', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function toggleBridgePortState(id, disabled) {
- try {
- const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ disabled })
- });
- if (res.ok) {
- loadBridge();
- fetchData(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deleteBridgePort(id) {
- const p = (state.bridgePorts || []).find(x => x.id === id);
- const iface = p ? p.interface : id;
- if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
- try {
- const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
- if (res.ok) {
- showToast('Port Detached', `${iface} removed from bridge`, 'success');
- loadBridge();
- fetchData(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // ----------------- Bridge VLANs -----------------
- function renderBridgeVLANs() {
- const tbody = document.getElementById('bridge-vlans-table-body');
- const empty = document.getElementById('bridge-empty-vlans');
- const countBadge = document.getElementById('bridge-vlans-count-badge');
- const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
- if (!tbody) return;
- tbody.innerHTML = '';
- populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
- const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
- if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
- if (vlans.length === 0) {
- empty?.classList.remove('hidden');
- return;
- }
- empty?.classList.add('hidden');
- vlans.forEach((v, idx) => {
- const tr = document.createElement('tr');
- tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
- const taggedHtml = (v.tagged && v.tagged.length > 0)
- ? 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(' ')
- : '<span class="text-slate-600">none</span>';
- const untaggedHtml = (v.untagged && v.untagged.length > 0)
- ? 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(' ')
- : '<span class="text-slate-600">none</span>';
- const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
- tr.innerHTML = `
- <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
- <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
- <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
- <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
- <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
- <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
- <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
- <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
- <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>
- <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
- <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
- </td>
- `;
- tbody.appendChild(tr);
- });
- }
- function openAddBridgeVLANModal() {
- document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
- document.getElementById('bridge-vlan-modal-id').value = '';
- populateBridgeSelect('bridge-vlan-modal-bridge');
- document.getElementById('bridge-vlan-modal-vlanids').value = '';
- document.getElementById('bridge-vlan-modal-comment').value = '';
- document.getElementById('bridge-vlan-modal-disabled').checked = false;
- updateBridgeVlanPortCheckboxes();
- document.getElementById('bridge-vlan-modal').classList.remove('hidden');
- }
- function openEditBridgeVLANModal(id) {
- const v = (state.bridgeVLANs || []).find(x => x.id === id);
- if (!v) return;
- document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
- document.getElementById('bridge-vlan-modal-id').value = v.id;
- populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
- document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
- document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
- document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
- updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
- document.getElementById('bridge-vlan-modal').classList.remove('hidden');
- }
- function closeBridgeVlanModal() {
- document.getElementById('bridge-vlan-modal').classList.add('hidden');
- }
- function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
- const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
- const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
- const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
- if (!taggedBox || !untaggedBox) return;
- // Ports belonging to the selected bridge
- const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
- if (memberPorts.length === 0) {
- taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
- untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
- return;
- }
- taggedBox.innerHTML = memberPorts.map(p => `
- <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
- <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">
- <span>${p.interface}</span>
- </label>
- `).join('');
- untaggedBox.innerHTML = memberPorts.map(p => `
- <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
- <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">
- <span>${p.interface}</span>
- </label>
- `).join('');
- }
- async function submitSaveBridgeVLAN(e) {
- e.preventDefault();
- const id = document.getElementById('bridge-vlan-modal-id').value;
- const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
- const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
- const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
- const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
- const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
- const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
- try {
- const res = await fetch(`${API_BASE}/bridge/vlans`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- id,
- bridge,
- vlan_ids: vlanIDs,
- tagged,
- untagged,
- comment,
- disabled
- })
- });
- if (res.ok) {
- showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
- closeBridgeVlanModal();
- loadBridge();
- } else {
- const err = await res.json();
- showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function toggleBridgeVLANState(id, disabled) {
- try {
- const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ disabled })
- });
- if (res.ok) loadBridge();
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deleteBridgeVLAN(id) {
- if (!confirm('Delete this bridge VLAN entry?')) return;
- try {
- const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
- if (res.ok) {
- showToast('Deleted', 'VLAN entry removed from bridge', 'success');
- loadBridge();
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // ----------------- Hosts / MAC Table -----------------
- async function loadBridgeHosts() {
- const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
- populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
- try {
- const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
- const res = await fetch(url);
- if (res.ok) {
- state.bridgeHosts = await res.json();
- renderBridgeHosts();
- }
- } catch (err) {
- console.error('Failed to load bridge hosts:', err);
- }
- }
- function renderBridgeHosts() {
- const tbody = document.getElementById('bridge-hosts-table-body');
- const empty = document.getElementById('bridge-empty-hosts');
- const countBadge = document.getElementById('bridge-hosts-count-badge');
- const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
- if (!tbody) return;
- tbody.innerHTML = '';
- const hosts = (state.bridgeHosts || []).filter(h => {
- if (!search) return true;
- return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
- });
- if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
- if (hosts.length === 0) {
- empty?.classList.remove('hidden');
- return;
- }
- empty?.classList.add('hidden');
- hosts.forEach(h => {
- const tr = document.createElement('tr');
- tr.className = 'hover:bg-slate-800/40 transition text-xs';
- let flagBadges = '';
- 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>';
- 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>';
- 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>';
- tr.innerHTML = `
- <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
- <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
- <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
- <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
- <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
- <td class="py-2.5 px-3">${flagBadges}</td>
- `;
- tbody.appendChild(tr);
- });
- }
- async function flushBridgeHosts() {
- const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
- if (!selBridge) {
- showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
- return;
- }
- if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
- try {
- const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ bridge: selBridge })
- });
- if (res.ok) {
- showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
- loadBridgeHosts();
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // ----------------- Helpers -----------------
- function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
- const sel = document.getElementById(selectId);
- if (!sel) return;
- const prevVal = currentVal || sel.value;
- sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
- (state.bridges || []).forEach(b => {
- const opt = document.createElement('option');
- opt.value = b.name;
- opt.innerText = `${b.name} (${b.ports_count} ports)`;
- if (b.name === prevVal) opt.selected = true;
- sel.appendChild(opt);
- });
- }
- function populateBridgePortCandidateSelect(selectId, currentVal = '') {
- const sel = document.getElementById(selectId);
- if (!sel) return;
- sel.innerHTML = '<option value="">(Select Interface...)</option>';
- // 1. Physical Interfaces
- const grpPhys = document.createElement('optgroup');
- grpPhys.label = 'Physical Interfaces';
- (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
- const opt = document.createElement('option');
- opt.value = i.name;
- opt.innerText = `${i.name} (${i.role || i.type})`;
- if (i.name === currentVal) opt.selected = true;
- grpPhys.appendChild(opt);
- });
- if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
- // 2. VLAN Sub-interfaces
- const grpVlans = document.createElement('optgroup');
- grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
- (state.vlans || []).forEach(v => {
- const opt = document.createElement('option');
- opt.value = v.name;
- opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
- if (v.name === currentVal) opt.selected = true;
- grpVlans.appendChild(opt);
- });
- if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
- // 3. EoIP Tunnels (MikroTik EoIP bridging!)
- const grpEoip = document.createElement('optgroup');
- grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
- (state.eoipTunnels || []).forEach(t => {
- const opt = document.createElement('option');
- opt.value = t.name;
- opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
- if (t.name === currentVal) opt.selected = true;
- grpEoip.appendChild(opt);
- });
- if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
- // 4. VXLAN Tunnels (MikroTik VXLAN bridging!)
- const grpVxlan = document.createElement('optgroup');
- grpVxlan.label = 'VXLAN Tunnels (Layer 2 Overlay)';
- (state.vxlanTunnels || []).forEach(t => {
- const opt = document.createElement('option');
- opt.value = t.name;
- opt.innerText = `${t.name} (VNI: ${t.vni}, Port: ${t.port})`;
- if (t.name === currentVal) opt.selected = true;
- grpVxlan.appendChild(opt);
- });
- if (grpVxlan.children.length > 0) sel.appendChild(grpVxlan);
- }
- // -------------------------------------------------------------
- // DebTik Routing Filters Management (/routing filter)
- // -------------------------------------------------------------
- if (!state.activeRoutingFilterTab) state.activeRoutingFilterTab = 'rules';
- if (!state.selectedFilterRow) state.selectedFilterRow = {};
- if (!state.rfSort) state.rfSort = {};
- function switchRoutingFilterTab(tab) {
- state.activeRoutingFilterTab = tab;
- const tabs = ['rules', 'community-lists', 'as-lists'];
- tabs.forEach(t => {
- const btn = document.getElementById(`tab-rf-${t}`);
- const content = document.getElementById(`tab-content-rf-${t}`);
- if (btn) {
- if (t === tab) {
- 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';
- } else {
- btn.className = 'px-3 py-1 text-xs font-semibold rounded text-slate-400 hover:text-white hover:bg-slate-800 transition';
- }
- }
- if (content) {
- if (t === tab) content.classList.remove('hidden');
- else content.classList.add('hidden');
- }
- });
- const chainContainer = document.getElementById('rf-chain-filter-container');
- if (chainContainer) {
- if (tab === 'rules') chainContainer.classList.remove('hidden');
- else chainContainer.classList.add('hidden');
- }
- renderRoutingFilters();
- }
- function selectFilterRow(tab, id) {
- if (state.selectedFilterRow[tab] === id) {
- delete state.selectedFilterRow[tab];
- } else {
- state.selectedFilterRow[tab] = id;
- }
- if (tab === 'rules') renderRoutingFilterRules();
- else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
- else if (tab === 'as-lists') renderRoutingFilterASLists();
- }
- function openRoutingFilterNewModal() {
- const tab = state.activeRoutingFilterTab || 'rules';
- if (tab === 'rules') openAddRoutingFilterModal();
- else if (tab === 'community-lists') openAddCommunityListModal();
- else if (tab === 'as-lists') openAddASListModal();
- }
- function toggleSelectedRoutingFilter(disabled) {
- const tab = state.activeRoutingFilterTab || 'rules';
- const id = state.selectedFilterRow[tab];
- if (!id) {
- showToast('Select Row', 'Please click on a row to select it first', 'info');
- return;
- }
- if (tab === 'rules') toggleRoutingFilterState(id, disabled);
- else if (tab === 'community-lists') toggleCommunityListState(id, disabled);
- else if (tab === 'as-lists') toggleASListState(id, disabled);
- }
- function removeSelectedRoutingFilter() {
- const tab = state.activeRoutingFilterTab || 'rules';
- const id = state.selectedFilterRow[tab];
- if (!id) {
- showToast('Select Row', 'Please click on a row to select it first', 'info');
- return;
- }
- if (tab === 'rules') deleteRoutingFilter(id);
- else if (tab === 'community-lists') deleteCommunityList(id);
- else if (tab === 'as-lists') deleteASList(id);
- }
- function searchRoutingFilters(q) {
- state.rfSearchQuery = (q || '').trim().toLowerCase();
- renderRoutingFilters();
- }
- function sortFilterTable(tab, col) {
- if (!state.rfSort) state.rfSort = {};
- if (!state.rfSort[tab]) state.rfSort[tab] = { col: col, asc: true };
- if (state.rfSort[tab].col === col) {
- state.rfSort[tab].asc = !state.rfSort[tab].asc;
- } else {
- state.rfSort[tab].col = col;
- state.rfSort[tab].asc = true;
- }
- const asc = state.rfSort[tab].asc;
- let list = [];
- if (tab === 'rules') list = state.routingFilters || [];
- else if (tab === 'community-lists') list = state.routingCommunityLists || [];
- else if (tab === 'as-lists') list = state.routingASLists || [];
- list.sort((a, b) => {
- let valA = a[col] ?? '';
- let valB = b[col] ?? '';
- if (col === 'flags') {
- valA = a.disabled ? 'X' : 'A';
- valB = b.disabled ? 'X' : 'A';
- }
- if (typeof valA === 'number' && typeof valB === 'number') {
- return asc ? valA - valB : valB - valA;
- }
- return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
- });
- const allCols = ['flags', 'rule_order', 'chain', 'rule', 'name', 'communities', 'range', 'regexp', 'comment'];
- allCols.forEach(c => {
- const el = document.getElementById(`sort-icon-${tab}-${c}`);
- if (el) el.innerText = (c === col) ? (asc ? '▲' : '▼') : '';
- });
- if (tab === 'rules') renderRoutingFilterRules();
- else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
- else if (tab === 'as-lists') renderRoutingFilterASLists();
- }
- function renderRoutingFilters() {
- const navBadge = document.getElementById('badge-filters-count');
- const allRules = state.routingFilters || [];
- if (navBadge) navBadge.innerText = allRules.length;
- // Populate chain filter select options and datalist
- const chainSelect = document.getElementById('routing-filter-chain-select');
- const chainDatalist = document.getElementById('dl-routing-chains');
- const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
- if (chainSelect) {
- const currentVal = state.filterChainSelected || 'all';
- chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
- uniqueChains.map(ch => {
- const count = allRules.filter(r => r.chain === ch).length;
- return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
- }).join('');
- chainSelect.value = currentVal;
- }
- if (chainDatalist) {
- chainDatalist.innerHTML = uniqueChains.map(ch => `<option value="${escapeHtml(ch)}">`).join('');
- }
- renderRoutingFilterRules();
- renderRoutingFilterCommunityLists();
- renderRoutingFilterASLists();
- }
- function filterRoutingFiltersByChain(chain) {
- state.filterChainSelected = chain;
- renderRoutingFilters();
- }
- // -------------------------------------------------------------
- // TAB 1: RULES (/routing filter rule)
- // -------------------------------------------------------------
- function renderRoutingFilterRules() {
- const tbody = document.getElementById('routing-filter-rules-tbody');
- if (!tbody) return;
- const empty = document.getElementById('rf-rules-empty');
- const statusCount = document.getElementById('rf-status-count');
- let list = (state.routingFilters || []).slice();
- if (state.filterChainSelected && state.filterChainSelected !== 'all') {
- list = list.filter(r => r.chain === state.filterChainSelected);
- }
- const q = state.rfSearchQuery;
- if (q) {
- list = list.filter(r =>
- (r.chain && r.chain.toLowerCase().includes(q)) ||
- (r.rule && r.rule.toLowerCase().includes(q)) ||
- (r.prefix && r.prefix.toLowerCase().includes(q)) ||
- (r.comment && r.comment.toLowerCase().includes(q))
- );
- }
- if (!state.rfSort?.['rules']) {
- list.sort((a, b) => {
- if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
- return (a.rule_order || 0) - (b.rule_order || 0);
- });
- }
- if (statusCount && (state.activeRoutingFilterTab === 'rules' || !state.activeRoutingFilterTab)) {
- statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
- }
- if (list.length === 0) {
- tbody.innerHTML = '';
- if (empty) empty.classList.remove('hidden');
- return;
- }
- if (empty) empty.classList.add('hidden');
- tbody.innerHTML = list.map(r => {
- const isSelected = state.selectedFilterRow?.['rules'] === r.id;
- const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
- const flagX = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
- const flagC = r.comment ? '<span class="text-amber-400 font-bold ml-1" title="Comment">C</span>' : '';
- let ruleDisplay = '';
- if (r.rule && r.rule.trim() !== '') {
- ruleDisplay = `<span class="text-emerald-400 font-mono font-medium">${escapeHtml(r.rule)}</span>`;
- } else {
- let conds = [];
- if (r.prefix) conds.push(`dst in ${escapeHtml(r.prefix)}`);
- if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${escapeHtml(r.match_protocol)}`);
- let act = r.action || 'accept';
- ruleDisplay = `<span class="text-slate-300 font-mono">if (${conds.length ? conds.join(' && ') : 'true'}) { ${escapeHtml(act)}; }</span>`;
- }
- return `
- <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'}">
- <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}${flagC}</td>
- <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
- <td class="py-2 px-3">
- <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>
- </td>
- <td class="py-2 px-3 break-all max-w-xl">${ruleDisplay}</td>
- <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
- <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
- <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>
- <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>
- <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'}">
- ${r.disabled ? 'Enable' : 'Disable'}
- </button>
- <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">
- Edit
- </button>
- <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">
- ✕
- </button>
- </td>
- </tr>
- `;
- }).join('');
- }
- // -------------------------------------------------------------
- // TAB 2: COMMUNITY LISTS (/routing filter community-list)
- // -------------------------------------------------------------
- function renderRoutingFilterCommunityLists() {
- const tbody = document.getElementById('routing-filter-comm-lists-tbody');
- if (!tbody) return;
- const empty = document.getElementById('rf-comm-lists-empty');
- const statusCount = document.getElementById('rf-status-count');
- let list = (state.routingCommunityLists || []).slice();
- const q = state.rfSearchQuery;
- if (q) {
- list = list.filter(cl =>
- (cl.name && cl.name.toLowerCase().includes(q)) ||
- (cl.comment && cl.comment.toLowerCase().includes(q)) ||
- (cl.communities && cl.communities.some(c => c.toLowerCase().includes(q)))
- );
- }
- if (statusCount && state.activeRoutingFilterTab === 'community-lists') {
- statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
- }
- if (list.length === 0) {
- tbody.innerHTML = '';
- if (empty) empty.classList.remove('hidden');
- return;
- }
- if (empty) empty.classList.add('hidden');
- tbody.innerHTML = list.map(cl => {
- const isSelected = state.selectedFilterRow?.['community-lists'] === cl.id;
- const flagA = !cl.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
- const flagX = cl.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
- const commBadges = (cl.communities || []).map(c =>
- `<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>`
- ).join(' ');
- return `
- <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'}">
- <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
- <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(cl.name)}</td>
- <td class="py-2 px-3 space-x-1">${commBadges || '<span class="text-slate-600">-</span>'}</td>
- <td class="py-2 px-3 font-mono text-slate-400">${escapeHtml(cl.regexp || '-')}</td>
- <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(cl.comment || '')}</td>
- <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
- <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'}">
- ${cl.disabled ? 'Enable' : 'Disable'}
- </button>
- <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">
- Edit
- </button>
- <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">
- ✕
- </button>
- </td>
- </tr>
- `;
- }).join('');
- }
- // -------------------------------------------------------------
- // TAB 4: AS LISTS (/routing filter num-list)
- // -------------------------------------------------------------
- function renderRoutingFilterASLists() {
- const tbody = document.getElementById('routing-filter-as-lists-tbody');
- if (!tbody) return;
- const empty = document.getElementById('rf-as-lists-empty');
- const statusCount = document.getElementById('rf-status-count');
- let list = (state.routingASLists || []).slice();
- const q = state.rfSearchQuery;
- if (q) {
- list = list.filter(al =>
- (al.name && al.name.toLowerCase().includes(q)) ||
- (al.range && al.range.toLowerCase().includes(q)) ||
- (al.comment && al.comment.toLowerCase().includes(q))
- );
- }
- if (statusCount && state.activeRoutingFilterTab === 'as-lists') {
- statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
- }
- if (list.length === 0) {
- tbody.innerHTML = '';
- if (empty) empty.classList.remove('hidden');
- return;
- }
- if (empty) empty.classList.add('hidden');
- tbody.innerHTML = list.map(al => {
- const isSelected = state.selectedFilterRow?.['as-lists'] === al.id;
- const flagA = !al.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
- const flagX = al.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
- return `
- <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'}">
- <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
- <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(al.name)}</td>
- <td class="py-2 px-3 font-mono text-purple-300">${escapeHtml(al.range)}</td>
- <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(al.comment || '')}</td>
- <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
- <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'}">
- ${al.disabled ? 'Enable' : 'Disable'}
- </button>
- <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">
- Edit
- </button>
- <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">
- ✕
- </button>
- </td>
- </tr>
- `;
- }).join('');
- }
- // -------------------------------------------------------------
- // SNIPPETS & WIZARD HELPERS
- // -------------------------------------------------------------
- function insertRuleSnippet(type) {
- const textarea = document.getElementById('modal-rf-rule');
- if (!textarea) return;
- let snippet = '';
- switch (type) {
- case 'accept-default':
- snippet = 'if (dst in 0.0.0.0/0) { accept; }';
- break;
- case 'drop-rfc1918':
- snippet = 'if (dst in 10.0.0.0/8 || dst in 172.16.0.0/12 || dst in 192.168.0.0/16) { reject; }';
- break;
- case 'len-24':
- snippet = 'if (dst-len > 24) { reject; }';
- break;
- case 'local-pref-150':
- snippet = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
- break;
- case 'as-prepend-2':
- snippet = 'set bgp-path-prepend 2; accept;';
- break;
- case 'set-comm':
- snippet = 'set bgp-communities.add 65000:100; accept;';
- break;
- case 'match-comm':
- snippet = 'if (bgp-communities includes 65000:100) { accept; }';
- break;
- case 'reject-all':
- snippet = 'reject;';
- break;
- }
- if (!snippet) return;
- if (!textarea.value.trim()) {
- textarea.value = snippet;
- } else {
- textarea.value = textarea.value.trim() + '\n' + snippet;
- }
- }
- function generateScriptFromWizard() {
- const pfx = (document.getElementById('modal-rf-prefix')?.value || '').trim();
- const pfxLen = (document.getElementById('modal-rf-prefix-len')?.value || '').trim();
- const proto = document.getElementById('modal-rf-protocol')?.value || 'any';
- const asp = (document.getElementById('modal-rf-as-path')?.value || '').trim();
- const comm = (document.getElementById('modal-rf-community')?.value || '').trim();
- const act = document.getElementById('modal-rf-action')?.value || 'accept';
- const lp = parseInt(document.getElementById('modal-rf-set-local-pref')?.value, 10) || 0;
- const prep = parseInt(document.getElementById('modal-rf-set-as-prepend')?.value, 10) || 0;
- const conds = [];
- if (pfx) {
- if (pfxLen) {
- if (pfxLen.includes('-')) {
- const parts = pfxLen.split('-');
- conds.push(`dst in ${pfx}{${parts[0].trim()},${parts[1].trim()}}`);
- } else {
- conds.push(`dst in ${pfx} && dst-len >= ${pfxLen}`);
- }
- } else {
- conds.push(`dst in ${pfx}`);
- }
- }
- if (proto && proto !== 'any') {
- conds.push(`protocol ${proto}`);
- }
- if (asp) {
- conds.push(`bgp-as-path "${asp}"`);
- }
- if (comm) {
- conds.push(`bgp-communities includes ${comm}`);
- }
- const actions = [];
- if (lp > 0) actions.push(`set bgp-local-pref ${lp};`);
- if (prep > 0) actions.push(`set bgp-path-prepend ${prep};`);
- if (act && act !== 'passthrough') {
- actions.push(`${act};`);
- }
- let code = '';
- if (conds.length > 0) {
- code = `if (${conds.join(' && ')}) {\n ${actions.join(' ')}\n}`;
- } else {
- code = actions.join(' ');
- }
- const textarea = document.getElementById('modal-rf-rule');
- if (textarea) textarea.value = code;
- }
- // -------------------------------------------------------------
- // MODAL CRUD: RULES (/routing filter rule)
- // -------------------------------------------------------------
- function openAddRoutingFilterModal(defaultChain = '') {
- const form = document.getElementById('routing-filter-form');
- if (form) form.reset();
- const idEl = document.getElementById('modal-rf-id');
- if (idEl) idEl.value = '';
- const titleEl = document.getElementById('modal-rf-title');
- if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
- const chainEl = document.getElementById('modal-rf-chain');
- if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
- const orderEl = document.getElementById('modal-rf-order');
- if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
- const ruleEl = document.getElementById('modal-rf-rule');
- if (ruleEl) ruleEl.value = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
- const disEl = document.getElementById('modal-rf-disabled');
- if (disEl) disEl.checked = false;
- const modal = document.getElementById('modal-routing-filter');
- if (modal) modal.classList.remove('hidden');
- }
- function openEditRoutingFilterModal(id) {
- const r = (state.routingFilters || []).find(item => item.id === id);
- if (!r) return;
- const idEl = document.getElementById('modal-rf-id');
- if (idEl) idEl.value = r.id;
- const titleEl = document.getElementById('modal-rf-title');
- if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
- const chainEl = document.getElementById('modal-rf-chain');
- if (chainEl) chainEl.value = r.chain || '';
- const orderEl = document.getElementById('modal-rf-order');
- if (orderEl) orderEl.value = r.rule_order || 10;
- const ruleEl = document.getElementById('modal-rf-rule');
- if (ruleEl) {
- if (r.rule) {
- ruleEl.value = r.rule;
- } else {
- let conds = [];
- if (r.prefix) conds.push(`dst in ${r.prefix}`);
- if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${r.match_protocol}`);
- let act = r.action || 'accept';
- ruleEl.value = `if (${conds.length ? conds.join(' && ') : 'true'}) { ${act}; }`;
- }
- }
- const comEl = document.getElementById('modal-rf-comment');
- if (comEl) comEl.value = r.comment || '';
- const disEl = document.getElementById('modal-rf-disabled');
- if (disEl) disEl.checked = !!r.disabled;
- const modal = document.getElementById('modal-routing-filter');
- if (modal) modal.classList.remove('hidden');
- }
- function closeRoutingFilterModal() {
- const modal = document.getElementById('modal-routing-filter');
- if (modal) modal.classList.add('hidden');
- }
- async function submitRoutingFilter(e) {
- if (e) e.preventDefault();
- const payload = {
- id: document.getElementById('modal-rf-id').value,
- chain: document.getElementById('modal-rf-chain').value.trim(),
- rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
- rule: document.getElementById('modal-rf-rule').value.trim(),
- comment: document.getElementById('modal-rf-comment').value.trim(),
- disabled: document.getElementById('modal-rf-disabled').checked
- };
- try {
- const res = await fetch(`${API_BASE}/routing/filters`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(payload)
- });
- if (res.ok) {
- closeRoutingFilterModal();
- showToast('Success', 'Routing filter rule saved', 'success');
- loadDynamicRouting();
- } else {
- const err = await res.json();
- showToast('Error', err.error || 'Failed to save filter rule', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function applyRoutingFilterForm() {
- const payload = {
- id: document.getElementById('modal-rf-id').value,
- chain: document.getElementById('modal-rf-chain').value.trim(),
- rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
- rule: document.getElementById('modal-rf-rule').value.trim(),
- comment: document.getElementById('modal-rf-comment').value.trim(),
- disabled: document.getElementById('modal-rf-disabled').checked
- };
- try {
- const res = await fetch(`${API_BASE}/routing/filters`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(payload)
- });
- if (res.ok) {
- const data = await res.json();
- if (data.id) document.getElementById('modal-rf-id').value = data.id;
- showToast('Applied', 'Routing filter configuration applied', 'success');
- loadDynamicRouting();
- } else {
- const err = await res.json();
- showToast('Error', err.error || 'Failed to apply filter rule', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function moveRoutingFilterOrder(id, delta) {
- const list = state.routingFilters || [];
- const idx = list.findIndex(r => r.id === id);
- if (idx < 0) return;
- const targetIdx = idx + delta;
- if (targetIdx < 0 || targetIdx >= list.length) return;
- const currentOrder = list[idx].rule_order || 10;
- const targetOrder = list[targetIdx].rule_order || 20;
- list[idx].rule_order = targetOrder;
- list[targetIdx].rule_order = currentOrder;
- try {
- await fetch(`${API_BASE}/routing/filters`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(list[idx])
- });
- await fetch(`${API_BASE}/routing/filters`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(list[targetIdx])
- });
- loadDynamicRouting();
- } catch (e) {
- console.error('Reorder error:', e);
- }
- }
- async function deleteRoutingFilter(id) {
- if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
- try {
- const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
- if (res.ok) {
- showToast('Deleted', 'Routing filter rule removed', 'info');
- loadDynamicRouting();
- } else {
- const err = await res.json();
- showToast('Error', err.error || 'Failed to delete rule', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function toggleRoutingFilterState(id, disabled) {
- try {
- const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ disabled })
- });
- if (res.ok) {
- showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
- loadDynamicRouting();
- } else {
- const err = await res.json();
- showToast('Error', err.error || 'Failed to toggle rule state', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // -------------------------------------------------------------
- // MODAL CRUD: COMMUNITY LISTS (/routing filter community-list)
- // -------------------------------------------------------------
- function openAddCommunityListModal() {
- document.getElementById('modal-rf-cl-id').value = '';
- document.getElementById('modal-rf-cl-title').innerText = 'Add BGP Community List';
- document.getElementById('modal-rf-cl-name').value = '';
- document.getElementById('modal-rf-cl-communities').value = '';
- document.getElementById('modal-rf-cl-regexp').value = '';
- document.getElementById('modal-rf-cl-comment').value = '';
- document.getElementById('modal-rf-cl-disabled').checked = false;
- document.getElementById('modal-rf-community-list').classList.remove('hidden');
- }
- function openEditCommunityListModal(id) {
- const cl = (state.routingCommunityLists || []).find(item => item.id === id);
- if (!cl) return;
- document.getElementById('modal-rf-cl-id').value = cl.id;
- document.getElementById('modal-rf-cl-title').innerText = 'Edit BGP Community List';
- document.getElementById('modal-rf-cl-name').value = cl.name || '';
- document.getElementById('modal-rf-cl-communities').value = (cl.communities || []).join(', ');
- document.getElementById('modal-rf-cl-regexp').value = cl.regexp || '';
- document.getElementById('modal-rf-cl-comment').value = cl.comment || '';
- document.getElementById('modal-rf-cl-disabled').checked = !!cl.disabled;
- document.getElementById('modal-rf-community-list').classList.remove('hidden');
- }
- function closeCommunityListModal() {
- document.getElementById('modal-rf-community-list').classList.add('hidden');
- }
- async function submitCommunityList(e) {
- e.preventDefault();
- const rawComms = document.getElementById('modal-rf-cl-communities').value;
- const comms = rawComms.split(',').map(c => c.trim()).filter(Boolean);
- const payload = {
- id: document.getElementById('modal-rf-cl-id').value,
- name: document.getElementById('modal-rf-cl-name').value.trim(),
- communities: comms,
- regexp: document.getElementById('modal-rf-cl-regexp').value.trim(),
- comment: document.getElementById('modal-rf-cl-comment').value.trim(),
- disabled: document.getElementById('modal-rf-cl-disabled').checked
- };
- try {
- const res = await fetch(`${API_BASE}/routing/filters/community-lists`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(payload)
- });
- if (res.ok) {
- closeCommunityListModal();
- showToast('Success', 'Community list saved', 'success');
- loadDynamicRouting();
- } else {
- const err = await res.json();
- showToast('Error', err.error || 'Failed to save community list', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deleteCommunityList(id) {
- if (!confirm('Are you sure you want to delete this community list?')) return;
- try {
- const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
- if (res.ok) {
- showToast('Deleted', 'Community list removed', 'info');
- loadDynamicRouting();
- } else {
- const err = await res.json();
- showToast('Error', err.error || 'Failed to delete community list', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function toggleCommunityListState(id, disabled) {
- try {
- const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}/state`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ disabled })
- });
- if (res.ok) {
- showToast('Status Updated', `Community list ${disabled ? 'disabled' : 'enabled'}`, 'info');
- loadDynamicRouting();
- } else {
- const err = await res.json();
- showToast('Error', err.error || 'Failed to update community list state', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // -------------------------------------------------------------
- // MODAL CRUD: AS LISTS (/routing filter num-list)
- // -------------------------------------------------------------
- function openAddASListModal() {
- document.getElementById('modal-rf-al-id').value = '';
- document.getElementById('modal-rf-al-title').innerText = 'Add AS Number List';
- document.getElementById('modal-rf-al-name').value = '';
- document.getElementById('modal-rf-al-range').value = '';
- document.getElementById('modal-rf-al-comment').value = '';
- document.getElementById('modal-rf-al-disabled').checked = false;
- document.getElementById('modal-rf-as-list').classList.remove('hidden');
- }
- function openEditASListModal(id) {
- const al = (state.routingASLists || []).find(item => item.id === id);
- if (!al) return;
- document.getElementById('modal-rf-al-id').value = al.id;
- document.getElementById('modal-rf-al-title').innerText = 'Edit AS Number List';
- document.getElementById('modal-rf-al-name').value = al.name || '';
- document.getElementById('modal-rf-al-range').value = al.range || '';
- document.getElementById('modal-rf-al-comment').value = al.comment || '';
- document.getElementById('modal-rf-al-disabled').checked = !!al.disabled;
- document.getElementById('modal-rf-as-list').classList.remove('hidden');
- }
- function closeASListModal() {
- document.getElementById('modal-rf-as-list').classList.add('hidden');
- }
- async function submitASList(e) {
- e.preventDefault();
- const payload = {
- id: document.getElementById('modal-rf-al-id').value,
- name: document.getElementById('modal-rf-al-name').value.trim(),
- range: document.getElementById('modal-rf-al-range').value.trim(),
- comment: document.getElementById('modal-rf-al-comment').value.trim(),
- disabled: document.getElementById('modal-rf-al-disabled').checked
- };
- try {
- const res = await fetch(`${API_BASE}/routing/filters/as-lists`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(payload)
- });
- if (res.ok) {
- closeASListModal();
- showToast('Success', 'AS number list saved', 'success');
- loadDynamicRouting();
- } else {
- const err = await res.json();
- showToast('Error', err.error || 'Failed to save AS list', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deleteASList(id) {
- if (!confirm('Are you sure you want to delete this AS list?')) return;
- try {
- const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
- if (res.ok) {
- showToast('Deleted', 'AS list removed', 'info');
- loadDynamicRouting();
- } else {
- const err = await res.json();
- showToast('Error', err.error || 'Failed to delete AS list', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function toggleASListState(id, disabled) {
- try {
- const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}/state`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ disabled })
- });
- if (res.ok) {
- showToast('Status Updated', `AS list ${disabled ? 'disabled' : 'enabled'}`, 'info');
- loadDynamicRouting();
- } else {
- const err = await res.json();
- showToast('Error', err.error || 'Failed to update AS list state', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // ==========================================
- // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
- // ==========================================
- function loadToolsView() {
- populateToolsInterfaces();
- switchToolsSubTab(state.activeToolsSubTab || 'ping');
- }
- function populateToolsInterfaces() {
- const pingSel = document.getElementById('tools-ping-iface');
- const traceSel = document.getElementById('tools-tr-iface');
- let opts = '<option value="">Auto (Default Route)</option>';
- if (Array.isArray(state.interfaces)) {
- state.interfaces.forEach(iface => {
- if (iface.name) {
- opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
- }
- });
- }
- if (pingSel) {
- const cur = pingSel.value;
- pingSel.innerHTML = opts;
- if (cur) pingSel.value = cur;
- }
- if (traceSel) {
- const cur = traceSel.value;
- traceSel.innerHTML = opts;
- if (cur) traceSel.value = cur;
- }
- }
- function switchToolsSubTab(subTab) {
- state.activeToolsSubTab = subTab;
- const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
- tabs.forEach(t => {
- const btn = document.getElementById(`tools-subtab-btn-${t}`);
- const view = document.getElementById(`tools-view-${t}`);
- if (btn) {
- if (t === subTab) {
- 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';
- } else {
- 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';
- }
- }
- if (view) {
- if (t === subTab) {
- view.classList.remove('hidden');
- } else {
- view.classList.add('hidden');
- }
- }
- });
- }
- function setPortPreset(port) {
- const input = document.getElementById('tools-port-num');
- if (input) input.value = port;
- }
- let pingAbortController = null;
- let tracerouteAbortController = null;
- function clearPingTable() {
- const tbody = document.getElementById('tools-ping-tbody');
- if (tbody) tbody.innerHTML = '';
- const rawEl = document.getElementById('tools-ping-raw');
- if (rawEl) rawEl.innerText = '';
- const sentEl = document.getElementById('tools-ping-stat-sent');
- if (sentEl) sentEl.innerText = '0';
- const recvEl = document.getElementById('tools-ping-stat-recv');
- if (recvEl) recvEl.innerText = '0';
- const lossEl = document.getElementById('tools-ping-stat-loss');
- if (lossEl) lossEl.innerText = '0%';
- const avgEl = document.getElementById('tools-ping-stat-avg');
- if (avgEl) avgEl.innerText = '0 ms';
- const minMaxEl = document.getElementById('tools-ping-stat-minmax');
- if (minMaxEl) minMaxEl.innerText = '-';
- const badge = document.getElementById('tools-ping-status-badge');
- if (badge) {
- badge.className = '';
- badge.innerText = '';
- }
- }
- function clearTracerouteTable() {
- const tbody = document.getElementById('tools-tr-tbody');
- if (tbody) tbody.innerHTML = '';
- const rawEl = document.getElementById('tools-tr-raw');
- if (rawEl) rawEl.innerText = '';
- const statHops = document.getElementById('tools-tr-hops-count');
- if (statHops) statHops.innerText = '0 Hops';
- }
- function resetPingButton() {
- const btn = document.getElementById('tools-ping-btn');
- const btnText = document.getElementById('tools-ping-btn-text');
- const spinner = document.getElementById('tools-ping-spinner');
- if (btn) {
- btn.disabled = false;
- 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';
- }
- if (btnText) btnText.innerText = 'Start Ping';
- if (spinner) spinner.classList.add('hidden');
- }
- function setPingRunningButton() {
- const btn = document.getElementById('tools-ping-btn');
- const btnText = document.getElementById('tools-ping-btn-text');
- const spinner = document.getElementById('tools-ping-spinner');
- if (btn) {
- btn.disabled = false;
- 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';
- }
- if (btnText) btnText.innerText = 'Stop Ping';
- if (spinner) spinner.classList.remove('hidden');
- }
- function resetTracerouteButton() {
- const btn = document.getElementById('tools-tr-btn');
- const btnText = document.getElementById('tools-tr-btn-text');
- const spinner = document.getElementById('tools-tr-spinner');
- if (btn) {
- btn.disabled = false;
- 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';
- }
- if (btnText) btnText.innerText = 'Start Traceroute';
- if (spinner) spinner.classList.add('hidden');
- }
- function setTracerouteRunningButton() {
- const btn = document.getElementById('tools-tr-btn');
- const btnText = document.getElementById('tools-tr-btn-text');
- const spinner = document.getElementById('tools-tr-spinner');
- if (btn) {
- btn.disabled = false;
- 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';
- }
- if (btnText) btnText.innerText = 'Stop Traceroute';
- if (spinner) spinner.classList.remove('hidden');
- }
- async function executePing(e) {
- if (e) e.preventDefault();
- // If already running, clicking the button stops the stream!
- if (pingAbortController) {
- pingAbortController.abort();
- pingAbortController = null;
- resetPingButton();
- showToast('Ping Stopped', 'Live ping stopped by user', 'info');
- return;
- }
- const target = document.getElementById('tools-ping-target')?.value?.trim();
- const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
- const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
- const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '3', 10);
- const iface = document.getElementById('tools-ping-iface')?.value || '';
- const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
- if (!target) {
- showToast('Input Required', 'Please enter a target host or IP', 'warning');
- return;
- }
- clearPingTable();
- const resCard = document.getElementById('tools-ping-results');
- if (resCard) resCard.classList.remove('hidden');
- pingAbortController = new AbortController();
- setPingRunningButton();
- try {
- const res = await fetch(`${API_BASE}/tools/ping/stream`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- target,
- count,
- size,
- timeout,
- interface: iface,
- dont_frag: dontFrag
- }),
- signal: pingAbortController.signal
- });
- if (!res.ok) {
- const errText = await res.text();
- showToast('Ping Error', errText || 'Failed to start live ping', 'error');
- resetPingButton();
- pingAbortController = null;
- return;
- }
- const reader = res.body.getReader();
- const decoder = new TextDecoder('utf-8');
- let buffer = '';
- while (true) {
- const { done, value } = await reader.read();
- if (done) break;
- buffer += decoder.decode(value, { stream: true });
- const blocks = buffer.split('\n\n');
- buffer = blocks.pop() || '';
- for (const block of blocks) {
- const trimmed = block.trim();
- if (!trimmed) continue;
- const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
- try {
- const evt = JSON.parse(line);
- handleLivePingEvent(evt);
- } catch (parseErr) {
- console.warn('Ping SSE parse error:', parseErr, line);
- }
- }
- }
- } catch (err) {
- if (err.name === 'AbortError') {
- // User aborted normally
- } else {
- showToast('Ping Error', err.message, 'error');
- }
- } finally {
- pingAbortController = null;
- resetPingButton();
- }
- }
- function handleLivePingEvent(evt) {
- const sentEl = document.getElementById('tools-ping-stat-sent');
- const recvEl = document.getElementById('tools-ping-stat-recv');
- const lossEl = document.getElementById('tools-ping-stat-loss');
- const avgEl = document.getElementById('tools-ping-stat-avg');
- const minMaxEl = document.getElementById('tools-ping-stat-minmax');
- const badge = document.getElementById('tools-ping-status-badge');
- const tbody = document.getElementById('tools-ping-tbody');
- const rawEl = document.getElementById('tools-ping-raw');
- if (evt.raw && rawEl) {
- rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
- rawEl.scrollTop = rawEl.scrollHeight;
- }
- if (evt.type === 'reply') {
- if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
- if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
- if (lossEl && evt.packet_loss_pct !== undefined) {
- lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
- lossEl.className = evt.packet_loss_pct === 0
- ? 'text-base font-bold font-mono text-emerald-400 mt-1'
- : (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');
- }
- if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
- if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
- minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
- }
- if (badge) {
- if (evt.packet_loss_pct === 0) {
- 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';
- badge.innerText = '100% OK';
- } else {
- 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';
- badge.innerText = `${evt.packet_loss_pct.toFixed(0)}% LOSS`;
- }
- }
- if (tbody) {
- const tr = document.createElement('tr');
- tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
- tr.innerHTML = `
- <td class="py-2 px-3 text-slate-300">#${evt.seq}</td>
- <td class="py-2 px-3 font-semibold text-white">${escapeHtml(evt.from)}</td>
- <td class="py-2 px-3 text-slate-400">${evt.bytes} bytes</td>
- <td class="py-2 px-3 text-slate-300">${evt.ttl}</td>
- <td class="py-2 px-3 font-bold text-amber-300">${evt.time_ms.toFixed(2)} ms</td>
- <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>
- `;
- tbody.appendChild(tr);
- }
- } else if (evt.type === 'timeout') {
- if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
- if (lossEl && evt.packet_loss_pct !== undefined) {
- lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
- 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';
- }
- if (badge) {
- 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';
- badge.innerText = `${evt.packet_loss_pct?.toFixed(0) || 100}% LOSS`;
- }
- if (tbody) {
- const tr = document.createElement('tr');
- tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs opacity-75';
- tr.innerHTML = `
- <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
- <td class="py-2 px-3 font-semibold text-slate-500 italic">Request timed out</td>
- <td class="py-2 px-3 text-slate-600">--</td>
- <td class="py-2 px-3 text-slate-600">--</td>
- <td class="py-2 px-3 font-bold text-slate-500">* * *</td>
- <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>
- `;
- tbody.appendChild(tr);
- }
- } else if (evt.type === 'unreach') {
- if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
- if (lossEl && evt.packet_loss_pct !== undefined) {
- lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
- lossEl.className = 'text-base font-bold font-mono text-rose-400 mt-1';
- }
- if (badge) {
- 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';
- badge.innerText = 'UNREACHABLE';
- }
- if (tbody) {
- const tr = document.createElement('tr');
- tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
- tr.innerHTML = `
- <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
- <td class="py-2 px-3 font-semibold text-rose-400">${escapeHtml(evt.from || 'Gateway')}</td>
- <td class="py-2 px-3 text-slate-600">--</td>
- <td class="py-2 px-3 text-slate-600">--</td>
- <td class="py-2 px-3 font-bold text-rose-400 text-xs">${escapeHtml(evt.message || 'Unreachable')}</td>
- <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>
- `;
- tbody.appendChild(tr);
- }
- } else if (evt.type === 'stats') {
- if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
- if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
- if (lossEl && evt.packet_loss_pct !== undefined) lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
- if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
- if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
- minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
- }
- } else if (evt.type === 'done') {
- 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');
- }
- }
- async function executeTraceroute(e) {
- if (e) e.preventDefault();
- if (tracerouteAbortController) {
- tracerouteAbortController.abort();
- tracerouteAbortController = null;
- resetTracerouteButton();
- showToast('Traceroute Stopped', 'Traceroute stopped by user', 'info');
- return;
- }
- const target = document.getElementById('tools-tr-target')?.value?.trim();
- const maxHops = parseInt(document.getElementById('tools-tr-maxhops')?.value || '15', 10);
- const protocol = document.getElementById('tools-tr-proto')?.value || 'icmp';
- const iface = document.getElementById('tools-tr-iface')?.value || '';
- const resolve = document.getElementById('tools-tr-resolve')?.checked || false;
- if (!target) {
- showToast('Input Required', 'Please enter a target host or IP', 'warning');
- return;
- }
- clearTracerouteTable();
- const resCard = document.getElementById('tools-tr-results');
- if (resCard) resCard.classList.remove('hidden');
- tracerouteAbortController = new AbortController();
- setTracerouteRunningButton();
- try {
- const res = await fetch(`${API_BASE}/tools/traceroute/stream`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- target,
- max_hops: maxHops,
- protocol,
- interface: iface,
- resolve
- }),
- signal: tracerouteAbortController.signal
- });
- if (!res.ok) {
- const errText = await res.text();
- showToast('Traceroute Error', errText || 'Failed to start traceroute', 'error');
- resetTracerouteButton();
- tracerouteAbortController = null;
- return;
- }
- const reader = res.body.getReader();
- const decoder = new TextDecoder('utf-8');
- let buffer = '';
- while (true) {
- const { done, value } = await reader.read();
- if (done) break;
- buffer += decoder.decode(value, { stream: true });
- const blocks = buffer.split('\n\n');
- buffer = blocks.pop() || '';
- for (const block of blocks) {
- const trimmed = block.trim();
- if (!trimmed) continue;
- const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
- try {
- const evt = JSON.parse(line);
- handleLiveTracerouteEvent(evt);
- } catch (parseErr) {
- console.warn('Traceroute SSE parse error:', parseErr, line);
- }
- }
- }
- } catch (err) {
- if (err.name === 'AbortError') {
- // User aborted normally
- } else {
- showToast('Traceroute Error', err.message, 'error');
- }
- } finally {
- tracerouteAbortController = null;
- resetTracerouteButton();
- }
- }
- function handleLiveTracerouteEvent(evt) {
- const statHops = document.getElementById('tools-tr-hops-count');
- const tbody = document.getElementById('tools-tr-tbody');
- const rawEl = document.getElementById('tools-tr-raw');
- if (evt.raw && rawEl) {
- rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
- rawEl.scrollTop = rawEl.scrollHeight;
- }
- if (evt.hops_count !== undefined && statHops) {
- statHops.innerText = `${evt.hops_count} Hops`;
- }
- if (evt.type === 'hop' && evt.hop && tbody) {
- const h = evt.hop;
- const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
- const rtt1 = Array.isArray(h.times_ms) && h.times_ms[0] ? `${h.times_ms[0]} ms` : (isTimeout ? '*' : '--');
- const rtt2 = Array.isArray(h.times_ms) && h.times_ms[1] ? `${h.times_ms[1]} ms` : (isTimeout ? '*' : '--');
- const displayHost = h.host && h.host !== h.ip ? `${escapeHtml(h.host)} (${escapeHtml(h.ip || '')})` : escapeHtml(h.ip || (isTimeout ? 'Request timed out' : '--'));
- const tr = document.createElement('tr');
- tr.className = `hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}`;
- tr.innerHTML = `
- <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
- <td class="py-2.5 px-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${displayHost}</td>
- <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt1)}</td>
- <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt2)}</td>
- <td class="py-2.5 px-3 text-right">
- ${isTimeout
- ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
- : '<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>'}
- </td>
- `;
- tbody.appendChild(tr);
- } else if (evt.type === 'done') {
- showToast('Traceroute Finished', `Traced ${evt.hops_count || 0} hops`, 'info');
- }
- }
- async function executeMTR(e) {
- if (e) e.preventDefault();
- const target = document.getElementById('tools-mtr-target')?.value?.trim();
- const cycles = parseInt(document.getElementById('tools-mtr-count')?.value || '3', 10);
- if (!target) {
- showToast('Input Required', 'Please enter a target host or IP', 'warning');
- return;
- }
- const btn = document.getElementById('tools-mtr-btn');
- const spinner = document.getElementById('tools-mtr-spinner');
- if (btn) btn.disabled = true;
- if (spinner) spinner.classList.remove('hidden');
- try {
- const res = await fetch(`${API_BASE}/tools/mtr`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ target, count: cycles })
- });
- const data = await res.json();
- if (!res.ok) {
- showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
- return;
- }
- const resCard = document.getElementById('tools-mtr-results');
- if (resCard) resCard.classList.remove('hidden');
- const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
- const statHops = document.getElementById('tools-mtr-hops-count');
- if (statHops) statHops.innerText = `${hopsCount} Hops`;
- const tbody = document.getElementById('tools-mtr-tbody');
- if (tbody) {
- if (hopsCount > 0) {
- tbody.innerHTML = data.hops.map(h => {
- 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');
- return `
- <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
- <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
- <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
- <td class="py-2.5 px-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
- <td class="py-2.5 px-3 text-slate-300">${h.sent}</td>
- <td class="py-2.5 px-3 text-slate-300">${h.last_ms.toFixed(1)}</td>
- <td class="py-2.5 px-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)}</td>
- <td class="py-2.5 px-3 text-emerald-400">${h.best_ms.toFixed(1)}</td>
- <td class="py-2.5 px-3 text-rose-400">${h.wrst_ms.toFixed(1)}</td>
- <td class="py-2.5 px-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
- </tr>
- `;
- }).join('');
- } else {
- tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
- }
- }
- const rawEl = document.getElementById('tools-mtr-raw');
- if (rawEl) rawEl.innerText = data.raw_output || 'No output';
- showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
- } catch (err) {
- showToast('MTR Error', err.message, 'error');
- } finally {
- if (btn) btn.disabled = false;
- if (spinner) spinner.classList.add('hidden');
- }
- }
- async function executeDNS(e) {
- if (e) e.preventDefault();
- const domain = document.getElementById('tools-dns-domain')?.value?.trim();
- const type = document.getElementById('tools-dns-type')?.value || 'A';
- const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
- if (!domain) {
- showToast('Input Required', 'Please enter a hostname or domain', 'warning');
- return;
- }
- const btn = document.getElementById('tools-dns-btn');
- const spinner = document.getElementById('tools-dns-spinner');
- if (btn) btn.disabled = true;
- if (spinner) spinner.classList.remove('hidden');
- try {
- const res = await fetch(`${API_BASE}/tools/dns`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ domain, type, server })
- });
- const data = await res.json();
- if (!res.ok) {
- showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
- return;
- }
- const resCard = document.getElementById('tools-dns-results');
- if (resCard) resCard.classList.remove('hidden');
- const metaEl = document.getElementById('tools-dns-meta');
- if (metaEl) metaEl.innerText = `Resolved in ${data.query_time_ms ?? 0} ms via ${escapeHtml(data.server || 'System DNS')}`;
- const tbody = document.getElementById('tools-dns-tbody');
- if (tbody) {
- if (Array.isArray(data.records) && data.records.length > 0) {
- tbody.innerHTML = data.records.map(r => `
- <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
- <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.name)}</td>
- <td class="py-2.5 px-3 text-slate-400">${r.ttl}s</td>
- <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.class || 'IN')}</td>
- <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>
- <td class="py-2.5 px-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
- </tr>
- `).join('');
- } else {
- 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>`;
- }
- }
- const rawEl = document.getElementById('tools-dns-raw');
- if (rawEl) rawEl.innerText = data.raw_output || 'No output';
- showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
- } catch (err) {
- showToast('DNS Error', err.message, 'error');
- } finally {
- if (btn) btn.disabled = false;
- if (spinner) spinner.classList.add('hidden');
- }
- }
- async function executePortProbe(e) {
- if (e) e.preventDefault();
- const target = document.getElementById('tools-port-target')?.value?.trim();
- const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
- const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
- if (!target || !port) {
- showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
- return;
- }
- const btn = document.getElementById('tools-port-btn');
- const spinner = document.getElementById('tools-port-spinner');
- if (btn) btn.disabled = true;
- if (spinner) spinner.classList.remove('hidden');
- try {
- const res = await fetch(`${API_BASE}/tools/port-probe`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ target, port, timeout })
- });
- const data = await res.json();
- if (!res.ok) {
- showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
- return;
- }
- const resCard = document.getElementById('tools-port-results');
- if (resCard) resCard.classList.remove('hidden');
- const banner = document.getElementById('tools-port-banner');
- const icon = document.getElementById('tools-port-icon');
- const title = document.getElementById('tools-port-title');
- const sub = document.getElementById('tools-port-sub');
- const latency = document.getElementById('tools-port-latency');
- if (data.open) {
- if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
- if (icon) {
- 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';
- icon.innerText = '✓';
- }
- if (title) {
- title.className = 'text-sm font-bold text-emerald-300';
- title.innerText = `PORT ${port} OPEN / LISTENING`;
- }
- if (sub) {
- sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
- sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
- }
- if (latency) {
- latency.className = 'text-base font-bold font-mono text-emerald-300';
- latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
- }
- } else {
- if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-800/50 flex items-center justify-between';
- if (icon) {
- 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';
- icon.innerText = '✕';
- }
- if (title) {
- title.className = 'text-sm font-bold text-rose-300';
- title.innerText = `PORT ${port} CLOSED / FILTERED`;
- }
- if (sub) {
- sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
- sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
- }
- if (latency) {
- latency.className = 'text-base font-bold font-mono text-slate-500';
- latency.innerText = '--';
- }
- }
- const rawEl = document.getElementById('tools-port-raw');
- 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'}`);
- showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
- } catch (err) {
- showToast('Probe Error', err.message, 'error');
- } finally {
- if (btn) btn.disabled = false;
- if (spinner) spinner.classList.add('hidden');
- }
- }
- // ==========================================
- // DHCP CLIENT (/ip dhcp-client) CONTROLLER
- // ==========================================
- async function loadDHCPClients(showToastMsg = false) {
- try {
- const [clientsRes, sumRes] = await Promise.all([
- fetch(`${API_BASE}/dhcp/clients`),
- fetch(`${API_BASE}/dhcp/clients/summary`)
- ]);
- if (clientsRes.ok) {
- state.dhcpClients = await clientsRes.json();
- }
- if (sumRes.ok) {
- state.dhcpSummary = await sumRes.json();
- }
- renderDHCPClients();
- updateDHCPSummaryCards();
- const bDhcp = document.getElementById('badge-dhcp-client-count');
- if (bDhcp && state.dhcpSummary) {
- bDhcp.innerText = state.dhcpSummary.total_clients || 0;
- }
- if (showToastMsg) {
- showToast('Refreshed', 'DHCP Client telemetry updated', 'info');
- }
- } catch (err) {
- console.error('Failed to load DHCP clients:', err);
- if (showToastMsg) {
- showToast('Notice', 'Unable to fetch DHCP client status', 'warning');
- }
- }
- }
- function updateDHCPSummaryCards() {
- const sum = state.dhcpSummary || {
- total_clients: (state.dhcpClients || []).length,
- bound_clients: (state.dhcpClients || []).filter(c => c.status === 'bound').length,
- searching_clients: (state.dhcpClients || []).filter(c => c.status === 'searching').length,
- disabled_clients: (state.dhcpClients || []).filter(c => !c.enabled).length
- };
- const totalEl = document.getElementById('dhcp-stat-total');
- const boundEl = document.getElementById('dhcp-stat-bound');
- const searchEl = document.getElementById('dhcp-stat-searching');
- const disEl = document.getElementById('dhcp-stat-disabled');
- if (totalEl) totalEl.innerText = sum.total_clients ?? 0;
- if (boundEl) boundEl.innerText = sum.bound_clients ?? 0;
- if (searchEl) searchEl.innerText = sum.searching_clients ?? 0;
- if (disEl) disEl.innerText = sum.disabled_clients ?? 0;
- }
- function renderDHCPClients() {
- const tbody = document.getElementById('dhcp-clients-tbody');
- const emptyState = document.getElementById('dhcp-clients-empty');
- if (!tbody) return;
- const clients = Array.isArray(state.dhcpClients) ? state.dhcpClients : [];
- if (clients.length === 0) {
- tbody.innerHTML = '';
- if (emptyState) emptyState.classList.remove('hidden');
- return;
- }
- if (emptyState) emptyState.classList.add('hidden');
- const sig = clients.map(c => `${c.id}:${c.status}:${c.ip_address}:${c.gateway}:${c.enabled}`).join(';');
- if (tbody.dataset.sig === sig) return;
- tbody.dataset.sig = sig;
- tbody.innerHTML = clients.map(c => {
- let statusBadge = '';
- if (!c.enabled) {
- 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>';
- } else if (c.status === 'bound') {
- 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>';
- } else if (c.status === 'searching') {
- 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>';
- } else if (c.status === 'stopped') {
- 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>';
- } else {
- 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>`;
- }
- 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>';
- const gwDisplay = c.gateway ? `<span class="text-slate-300">${escapeHtml(c.gateway)}</span>` : '<span class="text-slate-600">--</span>';
- const srvDisplay = c.dhcp_server ? `<span class="text-slate-300">${escapeHtml(c.dhcp_server)}</span>` : '<span class="text-slate-600">--</span>';
- 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>';
- const expDisplay = c.expires_in ? `<span class="text-purple-300">${escapeHtml(c.expires_in)}</span>` : '<span class="text-slate-600">--</span>';
- // Option flags
- const flags = [];
- 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>');
- 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>');
- 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>');
- 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>`);
- return `
- <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 text-xs transition">
- <td class="py-3 px-4">
- <div class="flex items-center gap-2">
- <span class="font-bold text-white text-sm">${escapeHtml(c.interface)}</span>
- ${c.comment ? `<span class="text-[11px] text-slate-400 font-sans italic">(${escapeHtml(c.comment)})</span>` : ''}
- </div>
- </td>
- <td class="py-3 px-4">${statusBadge}</td>
- <td class="py-3 px-4 font-mono">${ipDisplay}</td>
- <td class="py-3 px-4 font-mono">${gwDisplay}</td>
- <td class="py-3 px-4 font-mono">${srvDisplay}</td>
- <td class="py-3 px-4 font-mono text-[11px]">${dnsDisplay}</td>
- <td class="py-3 px-4 font-mono text-[11px]">${expDisplay}</td>
- <td class="py-3 px-4">
- <div class="flex flex-wrap gap-1 font-mono">${flags.join('')}</div>
- </td>
- <td class="py-3 px-4 text-right space-x-1.5 font-sans whitespace-nowrap">
- ${c.enabled ? `
- <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>
- <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>
- <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>
- ` : `
- <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>
- `}
- <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>
- <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>
- </td>
- </tr>
- `;
- }).join('');
- }
- function openDHCPClientModal(clientId = null) {
- const modal = document.getElementById('modal-dhcp-client');
- if (!modal) return;
- const title = document.getElementById('modal-dhcp-title');
- const idInput = document.getElementById('modal-dhcp-id');
- const ifaceSelect = document.getElementById('modal-dhcp-iface');
- const distInput = document.getElementById('modal-dhcp-distance');
- const commentInput = document.getElementById('modal-dhcp-comment');
- const defRouteCheck = document.getElementById('modal-dhcp-def-route');
- const peerDnsCheck = document.getElementById('modal-dhcp-peer-dns');
- const peerNtpCheck = document.getElementById('modal-dhcp-peer-ntp');
- const enabledCheck = document.getElementById('modal-dhcp-enabled');
- // Populate interfaces
- if (ifaceSelect) {
- let opts = '<option value="">Select interface...</option>';
- const allIfaces = state.interfaces || [];
- const allVlans = state.vlans || [];
- const usedIfaces = new Set((state.dhcpClients || []).map(c => c.interface));
- // Group 1: Physical & Bridge Interfaces
- opts += '<optgroup label="Physical & Bridge Interfaces">';
- allIfaces.filter(i => supportsDHCPClient(i)).forEach(i => {
- const isConfigured = usedIfaces.has(i.name) ? ' (Configured)' : '';
- opts += `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} [${escapeHtml(i.role || i.type)}]${isConfigured}</option>`;
- });
- opts += '</optgroup>';
- // Group 2: VLAN Interfaces
- if (allVlans.length > 0) {
- opts += '<optgroup label="802.1Q VLAN Sub-interfaces">';
- allVlans.forEach(v => {
- const isConfigured = usedIfaces.has(v.name) ? ' (Configured)' : '';
- opts += `<option value="${escapeHtml(v.name)}">${escapeHtml(v.name)} (VLAN ${v.vlan_id})${isConfigured}</option>`;
- });
- opts += '</optgroup>';
- }
- ifaceSelect.innerHTML = opts;
- }
- if (clientId) {
- const client = (state.dhcpClients || []).find(c => c.id === clientId);
- if (client) {
- if (title) title.innerText = `Edit DHCP Client: ${client.interface}`;
- if (idInput) idInput.value = client.id;
- if (ifaceSelect) {
- ifaceSelect.value = client.interface;
- ifaceSelect.disabled = true; // interface cannot be changed on edit
- }
- if (distInput) distInput.value = client.default_route_distance || 1;
- if (commentInput) commentInput.value = client.comment || '';
- if (defRouteCheck) defRouteCheck.checked = client.add_default_route !== false;
- if (peerDnsCheck) peerDnsCheck.checked = client.use_peer_dns !== false;
- if (peerNtpCheck) peerNtpCheck.checked = client.use_peer_ntp !== false;
- if (enabledCheck) enabledCheck.checked = client.enabled !== false;
- }
- } else {
- if (title) title.innerText = 'Add DHCP Client';
- if (idInput) idInput.value = '';
- if (ifaceSelect) {
- ifaceSelect.value = '';
- ifaceSelect.disabled = false;
- }
- if (distInput) distInput.value = 1;
- if (commentInput) commentInput.value = '';
- if (defRouteCheck) defRouteCheck.checked = true;
- if (peerDnsCheck) peerDnsCheck.checked = true;
- if (peerNtpCheck) peerNtpCheck.checked = true;
- if (enabledCheck) enabledCheck.checked = true;
- }
- modal.classList.remove('hidden');
- }
- function openDHCPClientModalForIface(ifaceName) {
- openDHCPClientModal();
- const ifaceSelect = document.getElementById('modal-dhcp-iface');
- if (ifaceSelect && ifaceName) {
- ifaceSelect.value = ifaceName;
- }
- }
- function closeDHCPClientModal() {
- const modal = document.getElementById('modal-dhcp-client');
- if (modal) modal.classList.add('hidden');
- }
- async function submitSaveDHCPClient(e) {
- if (e) e.preventDefault();
- const id = document.getElementById('modal-dhcp-id')?.value;
- const iface = document.getElementById('modal-dhcp-iface')?.value?.trim();
- const distance = parseInt(document.getElementById('modal-dhcp-distance')?.value || '1', 10);
- const comment = document.getElementById('modal-dhcp-comment')?.value?.trim() || '';
- const defRoute = document.getElementById('modal-dhcp-def-route')?.checked ?? true;
- const peerDns = document.getElementById('modal-dhcp-peer-dns')?.checked ?? true;
- const peerNtp = document.getElementById('modal-dhcp-peer-ntp')?.checked ?? true;
- const enabled = document.getElementById('modal-dhcp-enabled')?.checked ?? true;
- if (!id && !iface) {
- showToast('Input Required', 'Please select an interface for the DHCP client', 'warning');
- return;
- }
- try {
- let res;
- if (id) {
- // PUT update
- res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
- method: 'PUT',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- enabled,
- add_default_route: defRoute,
- default_route_distance: distance,
- use_peer_dns: peerDns,
- use_peer_ntp: peerNtp,
- comment
- })
- });
- } else {
- // POST create
- res = await fetch(`${API_BASE}/dhcp/clients`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- interface: iface,
- enabled,
- add_default_route: defRoute,
- default_route_distance: distance,
- use_peer_dns: peerDns,
- use_peer_ntp: peerNtp,
- comment
- })
- });
- }
- const data = await res.json();
- if (!res.ok) {
- showToast('Error', data.error || 'Failed to save DHCP client', 'error');
- return;
- }
- closeDHCPClientModal();
- showToast('Success', id ? 'DHCP Client updated successfully' : `DHCP Client activated on ${iface}`, 'success');
- await loadDHCPClients();
- fetchData(); // refresh interfaces list with new lease/status
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function toggleDHCPClientState(id, enabled) {
- try {
- const res = await fetch(`${API_BASE}/dhcp/clients/${id}/state`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ enabled })
- });
- const data = await res.json();
- if (!res.ok) {
- showToast('Error', data.error || 'Failed to toggle client state', 'error');
- return;
- }
- showToast('Updated', `DHCP client ${enabled ? 'enabled' : 'disabled'}`, 'info');
- await loadDHCPClients();
- fetchData();
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function renewDHCPClient(id) {
- try {
- showToast('Renewing...', 'Requesting DHCP lease renewal from upstream server', 'info');
- const res = await fetch(`${API_BASE}/dhcp/clients/${id}/renew`, {
- method: 'POST'
- });
- const data = await res.json();
- if (!res.ok) {
- showToast('Error', data.error || 'Failed to renew lease', 'error');
- return;
- }
- showToast('Lease Renewed', 'DHCP renewal signal sent successfully', 'success');
- setTimeout(() => {
- loadDHCPClients();
- fetchData();
- }, 1500);
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function releaseDHCPClient(id) {
- try {
- const res = await fetch(`${API_BASE}/dhcp/clients/${id}/release`, {
- method: 'POST'
- });
- const data = await res.json();
- if (!res.ok) {
- showToast('Error', data.error || 'Failed to release lease', 'error');
- return;
- }
- showToast('Lease Released', 'DHCP lease released from upstream server', 'info');
- await loadDHCPClients();
- fetchData();
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deleteDHCPClient(id, ifaceName) {
- if (!confirm(`Are you sure you want to remove the DHCP Client on ${ifaceName}? The interface will release its dynamic IP.`)) {
- return;
- }
- try {
- const res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
- method: 'DELETE'
- });
- const data = await res.json();
- if (!res.ok) {
- showToast('Error', data.error || 'Failed to delete DHCP client', 'error');
- return;
- }
- showToast('Deleted', `DHCP client removed from ${ifaceName}`, 'info');
- await loadDHCPClients();
- fetchData();
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // ==================== DHCP SERVER (/ip dhcp-server) ====================
- async function loadDHCPServer(populate = true) {
- try {
- const [sumRes, srvRes, netRes, leaseRes, optRes] = await Promise.all([
- fetch(`${API_BASE}/dhcp-server/summary`),
- fetch(`${API_BASE}/dhcp-server/servers`),
- fetch(`${API_BASE}/dhcp-server/networks`),
- fetch(`${API_BASE}/dhcp-server/leases`),
- fetch(`${API_BASE}/dhcp-server/options`)
- ]);
- if (sumRes.ok) state.dhcpServerSummary = await sumRes.json();
- if (srvRes.ok) state.dhcpServers = await srvRes.json();
- if (netRes.ok) state.dhcpNetworks = await netRes.json();
- if (leaseRes.ok) state.dhcpLeases = await leaseRes.json();
- if (optRes.ok) state.dhcpOptions = await optRes.json();
- const sum = state.dhcpServerSummary || {};
- const srvs = state.dhcpServers || [];
- const nets = state.dhcpNetworks || [];
- const leases = state.dhcpLeases || [];
- const opts = state.dhcpOptions || [];
- // KPI Cards
- const statActive = document.getElementById('dhcp-server-stat-active');
- if (statActive) {
- const activeCount = srvs.filter(s => s.running).length;
- statActive.innerText = `${activeCount} / ${srvs.length}`;
- }
- const statLeases = document.getElementById('dhcp-server-stat-leases');
- if (statLeases) {
- statLeases.innerText = leases.length;
- }
- const statLeasesSub = document.getElementById('dhcp-server-stat-leases-sub');
- if (statLeasesSub) {
- const dyn = leases.filter(l => l.dynamic).length;
- const st = leases.filter(l => !l.dynamic).length;
- statLeasesSub.innerText = `${dyn} dynamic, ${st} static`;
- }
- const statNetworks = document.getElementById('dhcp-server-stat-networks');
- if (statNetworks) {
- statNetworks.innerText = nets.length;
- }
- // Subtab Badges
- const bSrv = document.getElementById('dhcp-server-tab-badge-servers');
- if (bSrv) bSrv.innerText = srvs.length;
- const bNet = document.getElementById('dhcp-server-tab-badge-networks');
- if (bNet) bNet.innerText = nets.length;
- const bLease = document.getElementById('dhcp-server-tab-badge-leases');
- if (bLease) bLease.innerText = leases.length;
- const bOpt = document.getElementById('dhcp-server-tab-badge-options');
- if (bOpt) bOpt.innerText = opts.length;
- // Sidebar Badge
- const sideBadge = document.getElementById('badge-dhcp-server-count');
- if (sideBadge) sideBadge.innerText = leases.length || srvs.length;
- renderCurrentDHCPServerTab();
- } catch (err) {
- console.error('Failed to load DHCP Server:', err);
- }
- }
- function switchDHCPServerTab(tab) {
- state.dhcpServerTab = tab;
- const tabs = ['servers', 'networks', 'leases', 'options'];
- tabs.forEach(t => {
- const panel = document.getElementById(`dhcp-server-subtab-${t}`);
- const btn = document.getElementById(`dhcp-server-tab-btn-${t}`);
- if (panel) {
- if (t === tab) panel.classList.remove('hidden');
- else panel.classList.add('hidden');
- }
- if (btn) {
- if (t === tab) {
- 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';
- } else {
- 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';
- }
- }
- });
- const addBtn = document.getElementById('dhcp-server-primary-add-btn');
- if (addBtn) {
- if (tab === 'servers') addBtn.innerHTML = '<span>+ Add Server</span>';
- else if (tab === 'networks') addBtn.innerHTML = '<span>+ Add Network</span>';
- else if (tab === 'leases') addBtn.innerHTML = '<span>+ Add Static Lease</span>';
- else if (tab === 'options') addBtn.innerHTML = '<span>+ Add Option</span>';
- }
- renderCurrentDHCPServerTab();
- }
- function handleDHCPServerPrimaryAdd() {
- const tab = state.dhcpServerTab || 'servers';
- if (tab === 'servers') openAddDHCPServerModal();
- else if (tab === 'networks') openAddDHCPNetworkModal();
- else if (tab === 'leases') openAddDHCPStaticLeaseModal();
- else if (tab === 'options') openAddDHCPOptionModal();
- }
- function renderCurrentDHCPServerTab() {
- const tab = state.dhcpServerTab || 'servers';
- if (tab === 'servers') renderDHCPServers();
- else if (tab === 'networks') renderDHCPNetworks();
- else if (tab === 'leases') renderDHCPLeases();
- else if (tab === 'options') renderDHCPOptions();
- }
- function renderDHCPServers() {
- const tbody = document.getElementById('dhcp-server-tbody');
- const empty = document.getElementById('dhcp-server-empty');
- if (!tbody) return;
- const servers = state.dhcpServers || [];
- if (servers.length === 0) {
- tbody.innerHTML = '';
- empty?.classList.remove('hidden');
- return;
- }
- empty?.classList.add('hidden');
- const sig = servers.map(s => `${s.id}:${s.running}:${s.disabled}:${s.active_leases}:${s.interface}`).join(';');
- if (tbody.dataset.sig === sig) return;
- tbody.dataset.sig = sig;
- tbody.innerHTML = '';
- servers.forEach(s => {
- const tr = document.createElement('tr');
- tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
- tr.innerHTML = `
- <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(s.running, s.disabled)}</td>
- <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(s.name)}</td>
- <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(s.interface)}</td>
- <td class="py-2.5 px-3 font-mono font-semibold">${s.network ? `<span class="px-2 py-0.5 rounded text-[11px] bg-emerald-500/10 text-emerald-300 border border-emerald-500/20 font-bold">${escapeHtml(s.network)}</span>` : '<span class="text-slate-500 italic text-[11px]">Unassigned</span>'}</td>
- <td class="py-2.5 px-3 font-mono text-emerald-400">${escapeHtml(s.address_pool)}</td>
- <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(s.lease_time || '12h')}</td>
- <td class="py-2.5 px-3 font-mono text-slate-300">${s.authoritative ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}</td>
- <td class="py-2.5 px-3 font-mono text-cyan-300"><span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 border border-slate-700">${s.active_leases || 0}</span></td>
- <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(s.comment || '')}">${escapeHtml(s.comment || '-')}</td>
- <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
- <button onclick="toggleDHCPServerState('${s.id}', ${!s.disabled})" class="text-xs ${s.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${s.disabled ? 'Enable' : 'Disable'}</button>
- <button onclick="openEditDHCPServerModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
- <button onclick="deleteDHCPServer('${s.id}', '${escapeHtml(s.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
- </td>
- `;
- tbody.appendChild(tr);
- });
- }
- function renderDHCPNetworks() {
- const tbody = document.getElementById('dhcp-networks-tbody');
- const empty = document.getElementById('dhcp-networks-empty');
- if (!tbody) return;
- tbody.innerHTML = '';
- const networks = state.dhcpNetworks || [];
- if (networks.length === 0) {
- empty?.classList.remove('hidden');
- return;
- }
- empty?.classList.add('hidden');
- networks.forEach(n => {
- const tr = document.createElement('tr');
- tr.className = 'hover:bg-slate-800/40 transition text-xs';
- const dnsStr = (n.dns_servers || []).join(', ') || '-';
- const optionsChips = (n.dhcp_options || []).map(optId => {
- const opt = (state.dhcpOptions || []).find(o => o.id === optId);
- if (!opt) return '';
- return `<span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-cyan-300 border border-slate-700 inline-block mr-1 mb-0.5" title="${escapeHtml(opt.name)}: ${escapeHtml(opt.value)}">#${opt.code} ${escapeHtml(opt.name)}</span>`;
- }).filter(Boolean).join('');
- tr.innerHTML = `
- <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${escapeHtml(n.address)}</td>
- <td class="py-2.5 px-3 font-mono text-cyan-300 font-semibold">${escapeHtml(n.gateway || '-')}</td>
- <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(n.netmask || '-')}</td>
- <td class="py-2.5 px-3 font-mono text-slate-300 truncate max-w-[140px]" title="${escapeHtml(dnsStr)}">${escapeHtml(dnsStr)}</td>
- <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(n.domain || '-')}</td>
- <td class="py-2.5 px-3 font-mono">${optionsChips || '<span class="text-slate-600 font-sans">-</span>'}</td>
- <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(n.comment || '')}">${escapeHtml(n.comment || '-')}</td>
- <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
- <button onclick="openEditDHCPNetworkModal('${n.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
- <button onclick="deleteDHCPNetwork('${n.id}', '${escapeHtml(n.address)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
- </td>
- `;
- tbody.appendChild(tr);
- });
- }
- function renderDHCPLeases() {
- const tbody = document.getElementById('dhcp-leases-tbody');
- const empty = document.getElementById('dhcp-leases-empty');
- if (!tbody) return;
- tbody.innerHTML = '';
- const leases = state.dhcpLeases || [];
- if (leases.length === 0) {
- empty?.classList.remove('hidden');
- return;
- }
- empty?.classList.add('hidden');
- leases.forEach(l => {
- const tr = document.createElement('tr');
- tr.className = `hover:bg-slate-800/40 transition text-xs ${l.disabled ? 'opacity-50' : ''}`;
- const flag = l.dynamic ? '<span class="text-sky-400 font-bold" title="Dynamic">D</span>' : '<span class="text-purple-400 font-bold" title="Static Reservation">S</span>';
- const statusBadge = l.status === 'bound'
- ? '<span class="px-1.5 py-0.5 rounded text-[10px] bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 font-semibold font-mono">bound</span>'
- : l.status === 'static'
- ? '<span class="px-1.5 py-0.5 rounded text-[10px] bg-purple-500/20 text-purple-300 border border-purple-500/30 font-semibold font-mono">static</span>'
- : '<span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-400 border border-slate-700 font-mono">waiting</span>';
- const makeStaticBtn = l.dynamic
- ? `<button onclick="makeDHCPLeaseStatic('${escapeHtml(l.mac_address)}', '${escapeHtml(l.address)}', '${escapeHtml(l.hostname || '')}', '${escapeHtml(l.comment || '')}')" class="text-xs px-2 py-0.5 rounded bg-purple-500/20 text-purple-300 border border-purple-500/30 hover:bg-purple-500/30 font-medium">Make Static</button>`
- : `<button onclick="deleteDHCPStaticLease('${l.id}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Remove</button>`;
- tr.innerHTML = `
- <td class="py-2.5 px-3 text-center">${flag}</td>
- <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(l.address)}</td>
- <td class="py-2.5 px-3 font-mono text-cyan-300">${escapeHtml(l.mac_address)}</td>
- <td class="py-2.5 px-3 font-sans text-slate-200 font-medium">${escapeHtml(l.hostname || '*')}</td>
- <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(l.server || 'all')}</td>
- <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(l.expires_in || 'never')}</td>
- <td class="py-2.5 px-3">${statusBadge}</td>
- <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(l.comment || '')}">${escapeHtml(l.comment || '-')}</td>
- <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
- ${makeStaticBtn}
- </td>
- `;
- tbody.appendChild(tr);
- });
- }
- function renderDHCPOptions() {
- const tbody = document.getElementById('dhcp-options-tbody');
- const empty = document.getElementById('dhcp-options-empty');
- if (!tbody) return;
- tbody.innerHTML = '';
- const options = state.dhcpOptions || [];
- if (options.length === 0) {
- empty?.classList.remove('hidden');
- return;
- }
- empty?.classList.add('hidden');
- options.forEach(o => {
- const tr = document.createElement('tr');
- tr.className = 'hover:bg-slate-800/40 transition text-xs';
- tr.innerHTML = `
- <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(o.name)}</td>
- <td class="py-2.5 px-3 font-bold text-cyan-400 font-mono">${o.code}</td>
- <td class="py-2.5 px-3 font-mono text-emerald-400 break-all max-w-xs">${escapeHtml(o.value)}</td>
- <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-xs" title="${escapeHtml(o.comment || '')}">${escapeHtml(o.comment || '-')}</td>
- <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
- <button onclick="openEditDHCPOptionModal('${o.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
- <button onclick="deleteDHCPOption('${o.id}', '${escapeHtml(o.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
- </td>
- `;
- tbody.appendChild(tr);
- });
- }
- // ==================== MODALS & ACTIONS: SERVER ====================
- function populateDHCPNetworkSelect(elemId, selectedVal) {
- const sel = document.getElementById(elemId);
- if (!sel) return;
- sel.innerHTML = '<option value="">Select network subnet...</option>';
- const networks = state.dhcpNetworks || [];
- networks.forEach(n => {
- const opt = document.createElement('option');
- opt.value = n.address;
- opt.innerText = `${n.address} (Gateway: ${n.gateway || 'None'}${n.comment ? ' - ' + n.comment : ''})`;
- if (selectedVal && (selectedVal === n.address || selectedVal === n.id)) {
- opt.selected = true;
- }
- sel.appendChild(opt);
- });
- }
- function onDHCPServerNetworkChange() {
- const netSel = document.getElementById('dhcp-server-modal-network');
- if (!netSel) return;
- const netVal = netSel.value;
- if (!netVal) return;
- const poolInput = document.getElementById('dhcp-server-modal-pool');
- if (!poolInput) return;
- // Auto-calculate suggested address pool based on subnet CIDR
- const parts = netVal.split('/');
- const ip = parts[0];
- const cidr = parseInt(parts[1] || '24', 10);
- if (cidr === 24) {
- const octets = ip.split('.');
- if (octets.length === 4) {
- const base = `${octets[0]}.${octets[1]}.${octets[2]}`;
- poolInput.value = `${base}.10-${base}.254`;
- }
- }
- }
- function openAddDHCPServerModal() {
- document.getElementById('dhcp-server-modal-title').innerText = 'Add DHCP Server';
- document.getElementById('dhcp-server-modal-id').value = '';
- document.getElementById('dhcp-server-modal-name').value = `dhcp${(state.dhcpServers || []).length + 1}`;
- document.getElementById('dhcp-server-modal-pool').value = '192.168.88.10-192.168.88.254';
- document.getElementById('dhcp-server-modal-leasetime').value = '12h';
- document.getElementById('dhcp-server-modal-comment').value = '';
- document.getElementById('dhcp-server-modal-authoritative').checked = true;
- document.getElementById('dhcp-server-modal-disabled').checked = false;
- populateDHCPIfaceSelect('dhcp-server-modal-iface', '');
-
- const networks = state.dhcpNetworks || [];
- const defaultNet = networks.length > 0 ? networks[0].address : '';
- populateDHCPNetworkSelect('dhcp-server-modal-network', defaultNet);
- if (defaultNet) {
- onDHCPServerNetworkChange();
- }
- document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
- }
- function openEditDHCPServerModal(id) {
- const s = (state.dhcpServers || []).find(item => item.id === id);
- if (!s) return;
- document.getElementById('dhcp-server-modal-title').innerText = `Edit DHCP Server (${s.name})`;
- document.getElementById('dhcp-server-modal-id').value = s.id;
- document.getElementById('dhcp-server-modal-name').value = s.name;
- document.getElementById('dhcp-server-modal-pool').value = s.address_pool;
- document.getElementById('dhcp-server-modal-leasetime').value = s.lease_time || '12h';
- document.getElementById('dhcp-server-modal-comment').value = s.comment || '';
- document.getElementById('dhcp-server-modal-authoritative').checked = s.authoritative !== false;
- document.getElementById('dhcp-server-modal-disabled').checked = !!s.disabled;
- populateDHCPIfaceSelect('dhcp-server-modal-iface', s.interface);
- populateDHCPNetworkSelect('dhcp-server-modal-network', s.network || '');
- document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
- }
- function closeDHCPServerModal() {
- document.getElementById('dhcp-server-instance-modal').classList.add('hidden');
- }
- async function submitSaveDHCPServer(e) {
- e.preventDefault();
- const id = document.getElementById('dhcp-server-modal-id').value;
- const name = document.getElementById('dhcp-server-modal-name').value.trim();
- const iface = document.getElementById('dhcp-server-modal-iface').value;
- const network = document.getElementById('dhcp-server-modal-network').value.trim();
- const pool = document.getElementById('dhcp-server-modal-pool').value.trim();
- const leaseTime = document.getElementById('dhcp-server-modal-leasetime').value.trim() || '12h';
- const comment = document.getElementById('dhcp-server-modal-comment').value.trim();
- const authoritative = document.getElementById('dhcp-server-modal-authoritative').checked;
- const disabled = document.getElementById('dhcp-server-modal-disabled').checked;
- try {
- const res = await fetch(`${API_BASE}/dhcp-server/servers`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- id,
- name,
- interface: iface,
- network,
- address_pool: pool,
- lease_time: leaseTime,
- authoritative,
- disabled,
- comment
- })
- });
- if (res.ok) {
- showToast('DHCP Server Saved', `Server ${name} configured successfully`, 'success');
- closeDHCPServerModal();
- loadDHCPServer(false);
- fetchData(false);
- } else {
- const err = await res.text();
- showToast('Error', err, 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function toggleDHCPServerState(id, disabled) {
- try {
- const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}/state`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ disabled })
- });
- if (res.ok) {
- showToast('State Updated', disabled ? 'Server disabled' : 'Server enabled', 'info');
- loadDHCPServer(false);
- fetchData(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deleteDHCPServer(id, name) {
- if (!confirm(`Are you sure you want to delete DHCP Server "${name}"?`)) return;
- try {
- const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}`, { method: 'DELETE' });
- if (res.ok) {
- showToast('Deleted', `DHCP Server ${name} removed`, 'success');
- loadDHCPServer(false);
- fetchData(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // ==================== MODALS & ACTIONS: NETWORKS ====================
- function openAddDHCPNetworkModal() {
- document.getElementById('dhcp-network-modal-title').innerText = 'Add DHCP Network';
- document.getElementById('dhcp-network-modal-id').value = '';
- document.getElementById('dhcp-network-modal-address').value = '192.168.88.0/24';
- document.getElementById('dhcp-network-modal-gateway').value = '192.168.88.1';
- document.getElementById('dhcp-network-modal-dns').value = '192.168.88.1, 1.1.1.1, 8.8.8.8';
- document.getElementById('dhcp-network-modal-domain').value = 'lan';
- document.getElementById('dhcp-network-modal-netmask').value = '';
- document.getElementById('dhcp-network-modal-comment').value = '';
- renderDHCPNetworkOptionsCheckboxes([]);
- document.getElementById('dhcp-network-modal').classList.remove('hidden');
- }
- function openEditDHCPNetworkModal(id) {
- const n = (state.dhcpNetworks || []).find(item => item.id === id);
- if (!n) return;
- document.getElementById('dhcp-network-modal-title').innerText = `Edit DHCP Network (${n.address})`;
- document.getElementById('dhcp-network-modal-id').value = n.id;
- document.getElementById('dhcp-network-modal-address').value = n.address;
- document.getElementById('dhcp-network-modal-gateway').value = n.gateway || '';
- document.getElementById('dhcp-network-modal-dns').value = (n.dns_servers || []).join(', ');
- document.getElementById('dhcp-network-modal-domain').value = n.domain || '';
- document.getElementById('dhcp-network-modal-netmask').value = n.netmask || '';
- document.getElementById('dhcp-network-modal-comment').value = n.comment || '';
- renderDHCPNetworkOptionsCheckboxes(n.dhcp_options || []);
- document.getElementById('dhcp-network-modal').classList.remove('hidden');
- }
- function renderDHCPNetworkOptionsCheckboxes(selectedIds) {
- const container = document.getElementById('dhcp-network-modal-options-list');
- if (!container) return;
- container.innerHTML = '';
- const opts = state.dhcpOptions || [];
- if (opts.length === 0) {
- container.innerHTML = '<span class="text-slate-500 text-[11px] col-span-2">No custom options configured. Add some in the "Options" tab.</span>';
- return;
- }
- opts.forEach(o => {
- const isChecked = selectedIds.includes(o.id);
- const label = document.createElement('label');
- label.className = 'flex items-center space-x-2 text-slate-300 hover:text-white cursor-pointer';
- label.innerHTML = `
- <input type="checkbox" name="dhcp-net-opt" value="${o.id}" ${isChecked ? 'checked' : ''} class="rounded bg-slate-800 border-slate-700 text-emerald-600">
- <span class="truncate" title="${escapeHtml(o.name)} (Code ${o.code})">${escapeHtml(o.name)} <span class="text-cyan-400">#${o.code}</span></span>
- `;
- container.appendChild(label);
- });
- }
- function closeDHCPNetworkModal() {
- document.getElementById('dhcp-network-modal').classList.add('hidden');
- }
- async function submitSaveDHCPNetwork(e) {
- e.preventDefault();
- const id = document.getElementById('dhcp-network-modal-id').value;
- const address = document.getElementById('dhcp-network-modal-address').value.trim();
- const gateway = document.getElementById('dhcp-network-modal-gateway').value.trim();
- const dnsStr = document.getElementById('dhcp-network-modal-dns').value.trim();
- const domain = document.getElementById('dhcp-network-modal-domain').value.trim();
- const netmask = document.getElementById('dhcp-network-modal-netmask').value.trim();
- const comment = document.getElementById('dhcp-network-modal-comment').value.trim();
- const selectedOpts = [];
- document.querySelectorAll('input[name="dhcp-net-opt"]:checked').forEach(cb => selectedOpts.push(cb.value));
- const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
- try {
- const res = await fetch(`${API_BASE}/dhcp-server/networks`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- id,
- address,
- gateway,
- netmask,
- dns_servers: dnsServers,
- domain,
- dhcp_options: selectedOpts,
- comment
- })
- });
- if (res.ok) {
- showToast('Network Saved', `Subnet ${address} configured successfully`, 'success');
- closeDHCPNetworkModal();
- loadDHCPServer(false);
- fetchData(false);
- } else {
- const err = await res.text();
- showToast('Error', err, 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deleteDHCPNetwork(id, addr) {
- if (!confirm(`Are you sure you want to delete DHCP Network "${addr}"?`)) return;
- try {
- const res = await fetch(`${API_BASE}/dhcp-server/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
- if (res.ok) {
- showToast('Deleted', `Network ${addr} removed`, 'success');
- loadDHCPServer(false);
- fetchData(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // ==================== MODALS & ACTIONS: LEASES ====================
- function openAddDHCPStaticLeaseModal() {
- document.getElementById('dhcp-static-lease-modal-title').innerText = 'Add Static Lease Reservation';
- document.getElementById('dhcp-static-lease-modal-id').value = '';
- document.getElementById('dhcp-static-lease-modal-mac').value = '';
- document.getElementById('dhcp-static-lease-modal-ip').value = '';
- document.getElementById('dhcp-static-lease-modal-hostname').value = '';
- document.getElementById('dhcp-static-lease-modal-server').value = 'all';
- document.getElementById('dhcp-static-lease-modal-comment').value = '';
- document.getElementById('dhcp-static-lease-modal-disabled').checked = false;
- document.getElementById('dhcp-static-lease-modal').classList.remove('hidden');
- }
- function closeDHCPStaticLeaseModal() {
- document.getElementById('dhcp-static-lease-modal').classList.add('hidden');
- }
- async function submitSaveDHCPStaticLease(e) {
- e.preventDefault();
- const id = document.getElementById('dhcp-static-lease-modal-id').value;
- const mac = document.getElementById('dhcp-static-lease-modal-mac').value.trim();
- const ip = document.getElementById('dhcp-static-lease-modal-ip').value.trim();
- const hostname = document.getElementById('dhcp-static-lease-modal-hostname').value.trim();
- const server = document.getElementById('dhcp-static-lease-modal-server').value.trim() || 'all';
- const comment = document.getElementById('dhcp-static-lease-modal-comment').value.trim();
- const disabled = document.getElementById('dhcp-static-lease-modal-disabled').checked;
- try {
- const res = await fetch(`${API_BASE}/dhcp-server/leases/static`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- id,
- mac_address: mac,
- address: ip,
- hostname,
- server,
- comment,
- disabled
- })
- });
- if (res.ok) {
- showToast('Static Lease Saved', `IP ${ip} reserved for ${mac}`, 'success');
- closeDHCPStaticLeaseModal();
- loadDHCPServer(false);
- fetchData(false);
- } else {
- const err = await res.text();
- showToast('Error', err, 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deleteDHCPStaticLease(id) {
- if (!confirm('Are you sure you want to remove this static reservation?')) return;
- try {
- const res = await fetch(`${API_BASE}/dhcp-server/leases/${encodeURIComponent(id)}`, { method: 'DELETE' });
- if (res.ok) {
- showToast('Deleted', 'Static lease removed', 'success');
- loadDHCPServer(false);
- fetchData(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function makeDHCPLeaseStatic(mac, ip, hostname, comment) {
- try {
- const res = await fetch(`${API_BASE}/dhcp-server/leases/make-static`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- mac_address: mac,
- address: ip,
- hostname,
- comment: comment || 'Converted to static'
- })
- });
- if (res.ok) {
- showToast('Lease Made Static', `IP ${ip} permanently reserved for ${mac}`, 'success');
- loadDHCPServer(false);
- fetchData(false);
- } else {
- const err = await res.text();
- showToast('Error', err, 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // ==================== MODALS & ACTIONS: OPTIONS ====================
- function openAddDHCPOptionModal() {
- document.getElementById('dhcp-option-modal-title').innerText = 'Add DHCP Option';
- document.getElementById('dhcp-option-modal-id').value = '';
- document.getElementById('dhcp-option-modal-name').value = '';
- document.getElementById('dhcp-option-modal-code').value = '';
- document.getElementById('dhcp-option-modal-value').value = '';
- document.getElementById('dhcp-option-modal-comment').value = '';
- document.getElementById('dhcp-option-modal').classList.remove('hidden');
- }
- function openEditDHCPOptionModal(id) {
- const o = (state.dhcpOptions || []).find(item => item.id === id);
- if (!o) return;
- document.getElementById('dhcp-option-modal-title').innerText = `Edit DHCP Option (${o.name})`;
- document.getElementById('dhcp-option-modal-id').value = o.id;
- document.getElementById('dhcp-option-modal-name').value = o.name;
- document.getElementById('dhcp-option-modal-code').value = o.code;
- document.getElementById('dhcp-option-modal-value').value = o.value;
- document.getElementById('dhcp-option-modal-comment').value = o.comment || '';
- document.getElementById('dhcp-option-modal').classList.remove('hidden');
- }
- function closeDHCPOptionModal() {
- document.getElementById('dhcp-option-modal').classList.add('hidden');
- }
- async function submitSaveDHCPOption(e) {
- e.preventDefault();
- const id = document.getElementById('dhcp-option-modal-id').value;
- const name = document.getElementById('dhcp-option-modal-name').value.trim();
- const code = parseInt(document.getElementById('dhcp-option-modal-code').value);
- const value = document.getElementById('dhcp-option-modal-value').value.trim();
- const comment = document.getElementById('dhcp-option-modal-comment').value.trim();
- try {
- const res = await fetch(`${API_BASE}/dhcp-server/options`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ id, name, code, value, comment })
- });
- if (res.ok) {
- showToast('Option Saved', `DHCP option ${name} (#${code}) configured`, 'success');
- closeDHCPOptionModal();
- loadDHCPServer(false);
- fetchData(false);
- } else {
- const err = await res.text();
- showToast('Error', err, 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deleteDHCPOption(id, name) {
- if (!confirm(`Are you sure you want to delete DHCP Option "${name}"?`)) return;
- try {
- const res = await fetch(`${API_BASE}/dhcp-server/options/${encodeURIComponent(id)}`, { method: 'DELETE' });
- if (res.ok) {
- showToast('Deleted', `Option ${name} removed`, 'success');
- loadDHCPServer(false);
- fetchData(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // ==================== WIZARD: DHCP SETUP (MikroTik style) ====================
- function openDHCPServerSetupModal() {
- populateDHCPIfaceSelect('dhcp-wizard-iface', '');
- onDHCPWizardIfaceChange();
- document.getElementById('dhcp-setup-wizard-modal').classList.remove('hidden');
- }
- function closeDHCPServerSetupModal() {
- document.getElementById('dhcp-setup-wizard-modal').classList.add('hidden');
- }
- function onDHCPWizardIfaceChange() {
- const ifaceName = document.getElementById('dhcp-wizard-iface').value;
- const iface = (state.interfaces || []).find(i => i.name === ifaceName);
- let ip = '192.168.88.1';
- let prefix = '24';
- if (iface && iface.ip_address) {
- const parts = iface.ip_address.split('/');
- ip = parts[0];
- if (parts.length > 1) prefix = parts[1];
- }
- // Calculate subnet base (e.g. 192.168.88.0/24)
- const ipParts = ip.split('.');
- if (ipParts.length === 4) {
- const baseSpace = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.0/${prefix}`;
- const pool = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.10-${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.254`;
- document.getElementById('dhcp-wizard-space').value = baseSpace;
- document.getElementById('dhcp-wizard-gateway').value = ip;
- document.getElementById('dhcp-wizard-pool').value = pool;
- document.getElementById('dhcp-wizard-dns').value = `${ip}, 1.1.1.1, 8.8.8.8`;
- document.getElementById('dhcp-wizard-ntp').value = `${ip}`;
- }
- }
- async function submitDHCPServerSetupWizard(e) {
- e.preventDefault();
- const iface = document.getElementById('dhcp-wizard-iface').value;
- const space = document.getElementById('dhcp-wizard-space').value.trim();
- const gw = document.getElementById('dhcp-wizard-gateway').value.trim();
- const pool = document.getElementById('dhcp-wizard-pool').value.trim();
- const dnsStr = document.getElementById('dhcp-wizard-dns').value.trim();
- const leaseTime = document.getElementById('dhcp-wizard-leasetime').value.trim() || '12h';
- const ntpStr = document.getElementById('dhcp-wizard-ntp').value.trim();
- const tftp = document.getElementById('dhcp-wizard-tftp').value.trim();
- const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
- const ntpServers = ntpStr ? ntpStr.split(',').map(s => s.trim()).filter(Boolean) : [];
- try {
- const res = await fetch(`${API_BASE}/dhcp-server/setup`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- interface: iface,
- address_space: space,
- gateway: gw,
- address_pool: pool,
- dns_servers: dnsServers,
- lease_time: leaseTime,
- ntp_servers: ntpServers,
- next_server: tftp
- })
- });
- if (res.ok) {
- showToast('DHCP Setup Complete', `DHCP Server setup finished on ${iface}`, 'success');
- closeDHCPServerSetupModal();
- loadDHCPServer(false);
- fetchData(false);
- } else {
- const err = await res.text();
- showToast('Error', err, 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- function populateDHCPIfaceSelect(elemId, selectedVal) {
- const sel = document.getElementById(elemId);
- if (!sel) return;
- sel.innerHTML = '<option value="">Select interface...</option>';
- const ifaces = state.interfaces || [];
- ifaces.forEach(i => {
- if (i.name === 'lo') return;
- const opt = document.createElement('option');
- opt.value = i.name;
- const ipStr = i.ip_address ? ` (${i.ip_address})` : '';
- opt.textContent = `${i.name}${ipStr} [${i.role || i.type || 'interface'}]`;
- if (i.name === selectedVal) opt.selected = true;
- sel.appendChild(opt);
- });
- }
- // ==================== UNIVERSAL TABLE ORDERING / SORTING (WINBOX / WEBFIG STYLE) ====================
- function initTableSorting() {
- document.querySelectorAll('table').forEach(setupSortableTable);
- }
- function setupSortableTable(table) {
- const thead = table.querySelector('thead');
- const tbody = table.querySelector('tbody');
- if (!thead || !tbody) return;
- const headerRows = thead.querySelectorAll('tr');
- if (headerRows.length === 0) return;
- const ths = headerRows[headerRows.length - 1].querySelectorAll('th');
- ths.forEach((th, colIdx) => {
- if (th._sortBound) return;
- th._sortBound = true;
- const rawText = th.innerText.trim().toLowerCase();
- const isActionsCol = rawText === 'actions' || (rawText === 'action' && th.classList.contains('text-right'));
- const isCheckboxCol = !!th.querySelector('input[type="checkbox"]');
- const isExpandCol = (th.classList.contains('w-8') || th.classList.contains('w-6')) && !rawText;
- const isExplicitNoSort = th.classList.contains('no-sort') || th.getAttribute('data-sortable') === 'false';
- if (isActionsCol || isCheckboxCol || isExpandCol || isExplicitNoSort) {
- return;
- }
- th.classList.add('table-sortable', 'group');
- if (!th.title) th.title = 'Click to sort (Ascending / Descending / Default)';
- let icon = th.querySelector('.table-sort-icon');
- if (!icon) {
- icon = document.createElement('span');
- icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
- icon.innerHTML = '⇅';
- th.appendChild(icon);
- }
- th.addEventListener('click', (e) => {
- if (e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON' || e.target.closest('button, input')) return;
- handleHeaderClick(table, th, colIdx);
- });
- });
- if (!tbody._sortObserved) {
- tbody._sortObserved = true;
- let sortDebounceTimer = null;
- const observer = new MutationObserver((mutations) => {
- if (tbody._isSorting) return;
-
- const hasChildChanges = mutations.some(m => m.type === 'childList' && m.addedNodes.length > 0);
- if (!hasChildChanges) return;
- clearTimeout(sortDebounceTimer);
- sortDebounceTimer = setTimeout(() => {
- if (tbody._isSorting) return;
- if (table._activeSort && table._activeSort.dir !== 'none') {
- applyTableSort(table, table._activeSort.colIdx, table._activeSort.dir, false);
- } else {
- tagOriginalRowOrder(tbody);
- }
- }, 50);
- });
- tbody._sortObserver = observer;
- observer.observe(tbody, { childList: true });
- }
- tagOriginalRowOrder(tbody);
- }
- function tagOriginalRowOrder(tbody) {
- let idx = 0;
- Array.from(tbody.children).forEach(tr => {
- if (!tr.querySelector('td[colspan]')) {
- if (!tr.hasAttribute('data-orig-idx')) {
- tr.setAttribute('data-orig-idx', idx++);
- }
- }
- });
- }
- function handleHeaderClick(table, th, colIdx) {
- const currentSort = table._activeSort || { colIdx: -1, dir: 'none' };
- let newDir = 'asc';
- if (currentSort.colIdx === colIdx) {
- if (currentSort.dir === 'asc') newDir = 'desc';
- else if (currentSort.dir === 'desc') newDir = 'none';
- else newDir = 'asc';
- } else {
- newDir = 'asc';
- }
- table._activeSort = { colIdx, dir: newDir };
- updateHeaderIcons(table, colIdx, newDir);
- applyTableSort(table, colIdx, newDir, true);
- }
- function updateHeaderIcons(table, activeColIdx, dir) {
- const thead = table.querySelector('thead');
- if (!thead) return;
- const ths = thead.querySelectorAll('th');
- ths.forEach((th, idx) => {
- const icon = th.querySelector('.table-sort-icon');
- if (!icon) return;
- if (idx === activeColIdx && dir !== 'none') {
- icon.innerHTML = dir === 'asc' ? '▲' : '▼';
- icon.className = 'table-sort-icon text-cyan-400 font-bold opacity-100';
- th.classList.add('table-sorted-active');
- } else {
- icon.innerHTML = '⇅';
- icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
- th.classList.remove('table-sorted-active');
- }
- });
- }
- function applyTableSort(table, colIdx, dir, userInitiated) {
- const tbody = table.querySelector('tbody');
- if (!tbody || tbody.children.length <= 1) return;
- tbody._isSorting = true;
- tagOriginalRowOrder(tbody);
- // Group parent rows and any attached drawer/sub-rows
- const groups = [];
- let currentGroup = null;
- Array.from(tbody.children).forEach(tr => {
- if (tr.querySelector('td[colspan]')) {
- if (currentGroup) {
- currentGroup.subRows.push(tr);
- } else {
- groups.push({ mainRow: tr, subRows: [] });
- }
- } else {
- currentGroup = { mainRow: tr, subRows: [] };
- groups.push(currentGroup);
- }
- });
- if (dir === 'none') {
- groups.sort((a, b) => {
- const idxA = parseInt(a.mainRow.getAttribute('data-orig-idx') || '0', 10);
- const idxB = parseInt(b.mainRow.getAttribute('data-orig-idx') || '0', 10);
- return idxA - idxB;
- });
- } else {
- groups.sort((a, b) => {
- const cellA = a.mainRow.children[colIdx];
- const cellB = b.mainRow.children[colIdx];
- const res = compareTableCells(cellA, cellB);
- return dir === 'asc' ? res : -res;
- });
- }
- // Check if rows are already in correct order to avoid modifying DOM
- let alreadyOrdered = true;
- let childIdx = 0;
- for (const g of groups) {
- if (tbody.children[childIdx] !== g.mainRow) {
- alreadyOrdered = false;
- break;
- }
- childIdx++;
- for (const sub of g.subRows) {
- if (tbody.children[childIdx] !== sub) {
- alreadyOrdered = false;
- break;
- }
- childIdx++;
- }
- }
- if (alreadyOrdered) {
- tbody._isSorting = false;
- return;
- }
- // Disconnect observer while re-ordering to prevent recursion and thrashing
- if (tbody._sortObserver) {
- tbody._sortObserver.disconnect();
- }
- // Re-append rows in sorted order
- groups.forEach(g => {
- tbody.appendChild(g.mainRow);
- g.subRows.forEach(sub => tbody.appendChild(sub));
- });
- // Drain any queued mutations and re-connect observer
- if (tbody._sortObserver) {
- tbody._sortObserver.takeRecords();
- tbody._sortObserver.observe(tbody, { childList: true });
- }
- tbody._isSorting = false;
- }
- function getCellRawText(cell) {
- if (!cell) return '';
- if (cell.hasAttribute('data-sort-value')) return cell.getAttribute('data-sort-value');
- const input = cell.querySelector('input, select');
- if (input) {
- if (input.type === 'checkbox') return input.checked ? '1' : '0';
- return input.value;
- }
- return cell.innerText.trim();
- }
- function parseTrafficToNumber(str) {
- const m = str.match(/^([\d.,]+)\s*([KMGTkmgt]?[iI]?[Bb](?:ps|\/s)?)/);
- if (!m) return null;
- const num = parseFloat(m[1].replace(/,/g, ''));
- if (isNaN(num)) return null;
- const unit = m[2].toUpperCase();
- let mult = 1;
- if (unit.startsWith('K')) mult = 1024;
- else if (unit.startsWith('M')) mult = 1024 * 1024;
- else if (unit.startsWith('G')) mult = 1024 * 1024 * 1024;
- else if (unit.startsWith('T')) mult = 1024 * 1024 * 1024 * 1024;
- return num * mult;
- }
- function parseIpToNumber(str) {
- const clean = str.replace(/^[!~]/, '').trim();
- const m = clean.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,2}))?/);
- if (!m) return null;
- const o1 = parseInt(m[1], 10);
- const o2 = parseInt(m[2], 10);
- const o3 = parseInt(m[3], 10);
- const o4 = parseInt(m[4], 10);
- if (o1 > 255 || o2 > 255 || o3 > 255 || o4 > 255) return null;
- return ((o1 * 256 + o2) * 256 + o3) * 256 + o4;
- }
- function parseCompoundPackets(str) {
- const m = str.match(/^([\d,]+)p/);
- if (!m) return null;
- return parseInt(m[1].replace(/,/g, ''), 10);
- }
- function compareTableCells(cellA, cellB) {
- const a = getCellRawText(cellA);
- const b = getCellRawText(cellB);
- if (a === '' && b !== '') return 1;
- if (b === '' && a !== '') return -1;
- if (a === b) return 0;
- // 1. IP Addresses / CIDR
- const ipA = parseIpToNumber(a);
- const ipB = parseIpToNumber(b);
- if (ipA !== null && ipB !== null) return ipA - ipB;
- // 2. Packet counts (e.g. "1,250p / 45 KB")
- const pktA = parseCompoundPackets(a);
- const pktB = parseCompoundPackets(b);
- if (pktA !== null && pktB !== null) return pktA - pktB;
- // 3. Traffic / Throughput / Bytes (e.g. "1.2 MB", "500 KiB", "10 Gbps")
- const trafA = parseTrafficToNumber(a);
- const trafB = parseTrafficToNumber(b);
- if (trafA !== null && trafB !== null) return trafA - trafB;
- // 4. Numbers with '#' or formatted with commas (e.g. "#1", "24", "1,200")
- const cleanNumA = a.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
- const cleanNumB = b.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
- const numA = Number(cleanNumA);
- const numB = Number(cleanNumB);
- if (!isNaN(numA) && !isNaN(numB) && cleanNumA !== '' && cleanNumB !== '') {
- return numA - numB;
- }
- // 5. Natural case-insensitive string compare
- return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
- }
- // ==================== VRRP HIGH AVAILABILITY CONTROLLER ====================
- async function loadVRRP(showToastNotification = false) {
- try {
- const [instRes, sumRes] = await Promise.all([
- fetch(`${API_BASE}/vrrp/instances`),
- fetch(`${API_BASE}/vrrp/summary`)
- ]);
- if (instRes.ok) {
- state.vrrpInstances = await instRes.json();
- renderVRRP();
- }
- if (sumRes.ok) {
- state.vrrpSummary = await sumRes.json();
- renderVRRPSummary();
- }
- if (showToastNotification) {
- showToast('Refreshed', 'VRRP telemetry refreshed', 'info');
- }
- } catch (err) {
- console.error('Failed to load VRRP:', err);
- }
- }
- function renderVRRPSummary() {
- const s = state.vrrpSummary || { total_instances: 0, master_instances: 0, backup_instances: 0 };
- const elTotal = document.getElementById('vrrp-stat-total');
- if (elTotal) elTotal.innerText = s.total_instances || 0;
- const elMaster = document.getElementById('vrrp-stat-master');
- if (elMaster) elMaster.innerText = s.master_instances || 0;
- const elBackup = document.getElementById('vrrp-stat-backup');
- if (elBackup) elBackup.innerText = s.backup_instances || 0;
- const bCount = document.getElementById('badge-vrrp-count');
- if (bCount) bCount.innerText = s.total_instances || 0;
- const dot = document.getElementById('badge-vrrp-dot');
- if (dot) {
- if (s.master_instances > 0) {
- dot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
- } else if (s.backup_instances > 0) {
- dot.className = 'w-2 h-2 rounded-full bg-sky-400';
- } else {
- dot.className = 'w-2 h-2 rounded-full bg-slate-600';
- }
- }
- }
- function renderVRRP() {
- const tbody = document.getElementById('vrrp-table-tbody');
- const empty = document.getElementById('vrrp-table-empty');
- if (!tbody) return;
- tbody.innerHTML = '';
- const instances = state.vrrpInstances || [];
- if (instances.length === 0) {
- empty?.classList.remove('hidden');
- return;
- }
- empty?.classList.add('hidden');
- instances.forEach(inst => {
- const tr = document.createElement('tr');
- tr.className = `hover:bg-slate-800/40 transition text-xs ${inst.disabled ? 'opacity-50' : ''}`;
- // Render Flag: M (Master), B (Backup), F (Fault), X (Disabled)
- let flagHtml = `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] bg-slate-800 text-slate-500 border border-slate-700">-</span>`;
- if (inst.disabled) {
- flagHtml = `<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>`;
- } else if (inst.state === 'MASTER') {
- flagHtml = `<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="Master (Holding VIP)">M</span>`;
- } else if (inst.state === 'BACKUP') {
- flagHtml = `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] bg-sky-500/20 text-sky-400 border border-sky-500/40 shadow-sm" title="Backup (Standby)">B</span>`;
- } else if (inst.state === 'FAULT') {
- flagHtml = `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] bg-amber-500/20 text-amber-400 border border-amber-500/40 shadow-sm" title="Fault (Interface Down)">F</span>`;
- }
- // Render State Badge
- let stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-400 border border-slate-700">DISABLED</span>`;
- if (!inst.disabled) {
- if (inst.state === 'MASTER') {
- stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-emerald-500/20 text-emerald-300 border border-emerald-500/40 font-bold inline-flex items-center gap-1.5"><span class="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></span>MASTER</span>`;
- } else if (inst.state === 'BACKUP') {
- stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-sky-500/20 text-sky-300 border border-sky-500/40 font-bold inline-flex items-center gap-1.5"><span class="w-1.5 h-1.5 rounded-full bg-sky-400"></span>BACKUP</span>`;
- } else if (inst.state === 'FAULT') {
- stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-amber-500/20 text-amber-300 border border-amber-500/40 font-bold inline-flex items-center gap-1.5"><span class="w-1.5 h-1.5 rounded-full bg-amber-400"></span>FAULT</span>`;
- }
- }
- const vipsStr = (inst.virtual_ips || []).join(', ') || '-';
- tr.innerHTML = `
- <td class="py-2.5 px-3 text-center">${flagHtml}</td>
- <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(inst.name)}</td>
- <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(inst.interface)}</td>
- <td class="py-2.5 px-3 font-mono font-bold text-center text-white">${inst.vrid}</td>
- <td class="py-2.5 px-3 font-mono text-center text-slate-300 font-semibold">${inst.priority}</td>
- <td class="py-2.5 px-3 font-mono text-emerald-400 font-bold"><span class="px-2 py-0.5 rounded bg-emerald-500/10 border border-emerald-500/20">${escapeHtml(vipsStr)}</span></td>
- <td class="py-2.5 px-3 font-mono text-center text-slate-300">${inst.preempt ? '<span class="text-emerald-400 font-semibold">yes</span>' : '<span class="text-slate-500">no</span>'}</td>
- <td class="py-2.5 px-3 font-mono text-slate-400 text-[11px]">${escapeHtml(inst.virtual_mac || '-')}</td>
- <td class="py-2.5 px-3 text-center">${stateBadge}</td>
- <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(inst.comment || '')}">${escapeHtml(inst.comment || '-')}</td>
- <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
- <button onclick="toggleVRRPState('${inst.id}', ${!inst.disabled})" class="text-xs ${inst.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${inst.disabled ? 'Enable' : 'Disable'}</button>
- <button onclick="openEditVRRPModal('${inst.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
- <button onclick="deleteVRRP('${inst.id}', '${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
- </td>
- `;
- tbody.appendChild(tr);
- });
- }
- function populateVRRPIfaceSelect(elemId, selectedIface) {
- const sel = document.getElementById(elemId);
- if (!sel) return;
- sel.innerHTML = '<option value="">Select interface...</option>';
- const ifaces = state.interfaces || [];
- ifaces.forEach(i => {
- const opt = document.createElement('option');
- opt.value = i.name;
- opt.innerText = `${i.name} (${i.type || 'net'}${i.ip ? ' - ' + i.ip : ''})`;
- if (selectedIface && selectedIface === i.name) opt.selected = true;
- sel.appendChild(opt);
- });
- }
- function openAddVRRPModal() {
- document.getElementById('modal-vrrp-title').innerText = 'Add VRRP Instance';
- document.getElementById('modal-vrrp-id').value = '';
- document.getElementById('modal-vrrp-name').value = `vrrp${(state.vrrpInstances || []).length + 1}`;
- document.getElementById('modal-vrrp-vrid').value = 10 + (state.vrrpInstances || []).length;
- document.getElementById('modal-vrrp-priority').value = 100;
- document.getElementById('modal-vrrp-vip').value = '192.168.88.254/24';
- document.getElementById('modal-vrrp-version').value = '3';
- document.getElementById('modal-vrrp-interval').value = 1;
- document.getElementById('modal-vrrp-authtype').value = 'none';
- document.getElementById('modal-vrrp-authpass').value = '';
- document.getElementById('modal-vrrp-comment').value = '';
- document.getElementById('modal-vrrp-preempt').checked = true;
- document.getElementById('modal-vrrp-disabled').checked = false;
- populateVRRPIfaceSelect('modal-vrrp-iface', '');
- document.getElementById('modal-vrrp-instance').classList.remove('hidden');
- }
- function openEditVRRPModal(id) {
- const inst = (state.vrrpInstances || []).find(item => item.id === id);
- if (!inst) return;
- document.getElementById('modal-vrrp-title').innerText = `Edit VRRP Instance (${inst.name})`;
- document.getElementById('modal-vrrp-id').value = inst.id;
- document.getElementById('modal-vrrp-name').value = inst.name;
- document.getElementById('modal-vrrp-vrid').value = inst.vrid;
- document.getElementById('modal-vrrp-priority').value = inst.priority;
- document.getElementById('modal-vrrp-vip').value = (inst.virtual_ips || []).join(', ');
- document.getElementById('modal-vrrp-version').value = String(inst.version || 3);
- document.getElementById('modal-vrrp-interval').value = inst.interval || 1;
- document.getElementById('modal-vrrp-authtype').value = inst.auth_type || 'none';
- document.getElementById('modal-vrrp-authpass').value = inst.auth_password || '';
- document.getElementById('modal-vrrp-comment').value = inst.comment || '';
- document.getElementById('modal-vrrp-preempt').checked = inst.preempt !== false;
- document.getElementById('modal-vrrp-disabled').checked = !!inst.disabled;
- populateVRRPIfaceSelect('modal-vrrp-iface', inst.interface);
- document.getElementById('modal-vrrp-instance').classList.remove('hidden');
- }
- function closeVRRPModal() {
- document.getElementById('modal-vrrp-instance').classList.add('hidden');
- }
- async function submitSaveVRRP(e) {
- e.preventDefault();
- const id = document.getElementById('modal-vrrp-id').value;
- const name = document.getElementById('modal-vrrp-name').value.trim();
- const iface = document.getElementById('modal-vrrp-iface').value;
- const vrid = parseInt(document.getElementById('modal-vrrp-vrid').value, 10) || 1;
- const priority = parseInt(document.getElementById('modal-vrrp-priority').value, 10) || 100;
- const vipRaw = document.getElementById('modal-vrrp-vip').value.trim();
- const version = parseInt(document.getElementById('modal-vrrp-version').value, 10) || 3;
- const interval = parseInt(document.getElementById('modal-vrrp-interval').value, 10) || 1;
- const authType = document.getElementById('modal-vrrp-authtype').value;
- const authPass = document.getElementById('modal-vrrp-authpass').value.trim();
- const comment = document.getElementById('modal-vrrp-comment').value.trim();
- const preempt = document.getElementById('modal-vrrp-preempt').checked;
- const disabled = document.getElementById('modal-vrrp-disabled').checked;
- const vips = vipRaw.split(',').map(s => s.trim()).filter(Boolean);
- try {
- const res = await fetch(`${API_BASE}/vrrp/instances`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- id,
- name,
- interface: iface,
- vrid,
- priority,
- virtual_ips: vips,
- version,
- interval,
- auth_type: authType,
- auth_password: authPass,
- comment,
- preempt,
- disabled
- })
- });
- if (res.ok) {
- showToast('VRRP Saved', `VRRP instance ${name} configured`, 'success');
- closeVRRPModal();
- loadVRRP(false);
- fetchData(false);
- } else {
- const err = await res.text();
- showToast('Error', err, 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deleteVRRP(id, name) {
- if (!confirm(`Delete VRRP instance "${name}"?`)) return;
- try {
- const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
- if (res.ok) {
- showToast('Deleted', `VRRP instance ${name} removed`, 'info');
- loadVRRP(false);
- fetchData(false);
- } else {
- const err = await res.text();
- showToast('Error', err, 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function toggleVRRPState(id, disabled) {
- try {
- const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}/state`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ disabled })
- });
- if (res.ok) {
- showToast('State Updated', disabled ? 'VRRP disabled' : 'VRRP enabled', 'info');
- loadVRRP(false);
- fetchData(false);
- } else {
- const err = await res.text();
- showToast('Error', err, 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // Global observer for dynamically injected tables (e.g. inside modals or drawers)
- if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {
- let docSortDebounce = null;
- const docTableObserver = new MutationObserver((mutations) => {
- let needsInit = false;
- for (const m of mutations) {
- for (const node of m.addedNodes) {
- if (node.nodeType === 1) {
- if (node.tagName === 'TABLE' && !node.closest('tbody, thead')) {
- needsInit = true;
- break;
- } else if (node.querySelector && !node.closest('table') && node.querySelector('table')) {
- needsInit = true;
- break;
- }
- }
- }
- if (needsInit) break;
- }
- if (needsInit) {
- clearTimeout(docSortDebounce);
- docSortDebounce = setTimeout(initTableSorting, 100);
- }
- });
- docTableObserver.observe(document.body || document.documentElement, { childList: true, subtree: true });
- }
- // =========================================================================
- // BANDWIDTH TEST (BwTest) BENCHMARK ENGINE
- // =========================================================================
- const bwtestState = {
- running: false,
- pollTimer: null,
- eventSource: null,
- chartPoints: [],
- maxChartPoints: 60,
- serverConfig: null,
- peakTx: 0,
- peakRx: 0,
- targetDuration: 10,
- lastSampleElapsed: -1,
- sessionID: null
- };
- async function loadBwTestView() {
- resizeBwTestCanvas();
- await Promise.all([fetchBwTestServerStatus(), loadBwTestHistory(), checkActiveBwTest()]);
- }
- async function fetchBwTestServerStatus() {
- try {
- const res = await fetch(`${API_BASE}/tools/bwtest/server`);
- if (!res.ok) return;
- const s = await res.json();
- bwtestState.serverConfig = s;
- // Update indicator and badges
- const indicator = document.getElementById('bwtest-server-indicator');
- const badge = document.getElementById('bwtest-server-badge');
- const sideBadge = document.getElementById('badge-bwtest-server');
- if (s.enabled && s.running) {
- if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
- if (badge) {
- badge.innerText = `Port ${s.port} (Active)`;
- badge.className = 'text-emerald-400 font-bold';
- }
- if (sideBadge) {
- sideBadge.innerText = s.port;
- sideBadge.className = 'text-[10px] bg-emerald-950 text-emerald-300 border border-emerald-800/40 px-1.5 py-0.2 rounded-full font-mono';
- }
- } else {
- if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-slate-600';
- if (badge) {
- badge.innerText = `Disabled`;
- badge.className = 'text-slate-500 font-bold';
- }
- if (sideBadge) {
- sideBadge.innerText = 'Off';
- sideBadge.className = 'text-[10px] bg-slate-800 text-slate-500 border border-slate-700 px-1.5 py-0.2 rounded-full font-mono';
- }
- }
- // Modal fields
- const toggle = document.getElementById('bwtest-server-enable-toggle');
- const serverModal = document.getElementById('modal-bwtest-server');
- const editing = serverModal && !serverModal.classList.contains('hidden');
- if (toggle && !editing) toggle.checked = !!s.enabled;
- const portInp = document.getElementById('bwtest-server-port-input');
- if (portInp && !editing) portInp.value = s.port || 2000;
- const actSess = document.getElementById('bwtest-modal-active-sessions');
- if (actSess) actSess.innerText = s.active_sessions || 0;
- const totServ = document.getElementById('bwtest-modal-total-served');
- if (totServ) totServ.innerText = s.total_sessions_served || 0;
- const totBytes = document.getElementById('bwtest-modal-total-bytes');
- if (totBytes) totBytes.innerText = formatBytes(s.total_bytes_processed || 0);
- } catch (err) {
- console.error('Failed to fetch BwTest server status:', err);
- }
- }
- function openBwTestServerModal() {
- const cfg = bwtestState.serverConfig;
- if (cfg) {
- document.getElementById('bwtest-server-enable-toggle').checked = !!cfg.enabled;
- document.getElementById('bwtest-server-port-input').value = cfg.port || 2000;
- }
- fetchBwTestServerStatus();
- document.getElementById('modal-bwtest-server')?.classList.remove('hidden');
- }
- function closeBwTestServerModal() {
- document.getElementById('modal-bwtest-server')?.classList.add('hidden');
- }
- async function submitBwTestServerSettings(e) {
- e.preventDefault();
- const enabled = document.getElementById('bwtest-server-enable-toggle').checked;
- const port = parseInt(document.getElementById('bwtest-server-port-input').value, 10) || 2000;
- try {
- const res = await fetch(`${API_BASE}/tools/bwtest/server`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ enabled, port, listen_addr: '0.0.0.0', allow_anonymous: true })
- });
- if (!res.ok) {
- const err = await res.json();
- throw new Error(err.error || 'Failed to update server configuration');
- }
- showToast('BwTest Server', `Bandwidth Test server updated (Port ${port})`, 'success');
- closeBwTestServerModal();
- fetchBwTestServerStatus();
- } catch (err) {
- showToast('Server Configuration Error', err.message, 'error');
- }
- }
- function setBwTestTarget(target) {
- const inp = document.getElementById('bwtest-input-target');
- if (inp) inp.value = target;
- }
- function setBwTestProtocol(proto) {
- const hiddenInp = document.getElementById('bwtest-input-protocol');
- if (hiddenInp) hiddenInp.value = proto;
- const btnUdp = document.getElementById('bwtest-proto-udp');
- const btnTcp = document.getElementById('bwtest-proto-tcp');
- const badge = document.getElementById('bwtest-proto-badge');
- const pktField = document.getElementById('bwtest-field-pktsize');
- const activeUdpCls = 'py-2.5 px-3 rounded-lg text-xs font-bold border transition text-center bg-emerald-600/20 border-emerald-500/50 text-emerald-300 shadow-sm flex items-center justify-center gap-2';
- const activeTcpCls = 'py-2.5 px-3 rounded-lg text-xs font-bold border transition text-center bg-blue-600/20 border-blue-500/50 text-blue-300 shadow-sm flex items-center justify-center gap-2';
- const inactiveCls = 'py-2.5 px-3 rounded-lg text-xs font-medium border border-slate-800 bg-slate-950 text-slate-400 hover:text-white transition text-center flex items-center justify-center gap-2';
- if (proto === 'udp') {
- if (btnUdp) {
- btnUdp.className = activeUdpCls;
- const dot = btnUdp.querySelector('span');
- if (dot) dot.className = 'w-2 h-2 rounded-full bg-emerald-400';
- }
- if (btnTcp) {
- btnTcp.className = inactiveCls;
- const dot = btnTcp.querySelector('span');
- if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
- }
- if (badge) {
- badge.innerText = 'UDP Mode (RFC 3550 Jitter + Loss %)';
- badge.className = 'text-[10px] font-mono text-emerald-400 bg-emerald-500/10 px-2 py-0.5 rounded border border-emerald-500/20';
- }
- if (pktField) pktField.classList.remove('opacity-40');
- } else {
- if (btnUdp) {
- btnUdp.className = inactiveCls;
- const dot = btnUdp.querySelector('span');
- if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
- }
- if (btnTcp) {
- btnTcp.className = activeTcpCls;
- const dot = btnTcp.querySelector('span');
- if (dot) dot.className = 'w-2 h-2 rounded-full bg-blue-400';
- }
- if (badge) {
- badge.innerText = 'TCP Mode (Sliding Window Throughput)';
- badge.className = 'text-[10px] font-mono text-blue-400 bg-blue-500/10 px-2 py-0.5 rounded border border-blue-500/20';
- }
- if (pktField) pktField.classList.add('opacity-40');
- }
- }
- function setBwTestDirection(dir) {
- const hiddenInp = document.getElementById('bwtest-input-direction');
- if (hiddenInp) hiddenInp.value = dir;
- const btnBoth = document.getElementById('bwtest-dir-both');
- const btnTx = document.getElementById('bwtest-dir-tx');
- const btnRx = document.getElementById('bwtest-dir-rx');
- const activeCls = 'py-2 px-2 rounded-lg text-xs font-bold border transition text-center bg-emerald-600/20 border-emerald-500/50 text-emerald-300 shadow-sm';
- const inactiveCls = 'py-2 px-2 rounded-lg text-xs font-medium border border-slate-800 bg-slate-950 text-slate-400 hover:text-white transition text-center';
- if (btnBoth) btnBoth.className = dir === 'both' ? activeCls : inactiveCls;
- if (btnTx) btnTx.className = dir === 'tx' ? activeCls : inactiveCls;
- if (btnRx) btnRx.className = dir === 'rx' ? activeCls : inactiveCls;
- }
- function setBwTestLimit(bps) {
- const sel = document.getElementById('bwtest-input-limit');
- if (sel) sel.value = String(bps);
- }
- async function checkActiveBwTest() {
- try {
- const res = await fetch(`${API_BASE}/tools/bwtest/status`);
- if (!res.ok) return;
- const st = await res.json();
- if (st.running) {
- setBwTestRunningUI(true);
- processBwTestStatus(st);
- startBwTestTelemetry();
- }
- } catch (err) {
- console.error('Failed to check active BwTest:', err);
- }
- }
- async function startBwTest(e) {
- if (e && e.preventDefault) e.preventDefault();
- const target = document.getElementById('bwtest-input-target').value.trim() || '127.0.0.1';
- const port = parseInt(document.getElementById('bwtest-input-port').value, 10) || 2000;
- const direction = document.getElementById('bwtest-input-direction').value || 'both';
- const protocol = document.getElementById('bwtest-input-protocol').value || 'udp';
- const bandwidth_limit = parseInt(document.getElementById('bwtest-input-limit').value, 10) || 0;
- const packet_size = parseInt(document.getElementById('bwtest-input-pktsize').value, 10) || 1472;
- const streams = parseInt(document.getElementById('bwtest-input-streams').value, 10) || 1;
- const duration = parseInt(document.getElementById('bwtest-input-duration').value, 10);
- bwtestState.targetDuration = duration;
- bwtestState.chartPoints = [];
- bwtestState.peakTx = 0;
- bwtestState.peakRx = 0;
- bwtestState.lastSampleElapsed = -1;
- bwtestState.sessionID = null;
- // Clear UI elements
- document.getElementById('bwtest-stat-tx-mbps').innerText = '0.00';
- document.getElementById('bwtest-stat-tx-peak').innerText = '0.00 Mbps';
- document.getElementById('bwtest-stat-tx-pkts').innerText = '0';
- document.getElementById('bwtest-stat-rx-mbps').innerText = '0.00';
- document.getElementById('bwtest-stat-rx-peak').innerText = '0.00 Mbps';
- document.getElementById('bwtest-stat-rx-pkts').innerText = '0';
- document.getElementById('bwtest-stat-loss').innerText = '0.0%';
- document.getElementById('bwtest-stat-jitter').innerText = '0.00 ms';
- document.getElementById('bwtest-stat-time').innerText = '0.0s';
- document.getElementById('bwtest-stat-data').innerText = '0.0 MB';
- document.getElementById('bwtest-stat-target-dur').innerText = duration > 0 ? `/ ${duration}s` : '/ ∞';
- const tbody = document.getElementById('bwtest-samples-tbody');
- if (tbody) tbody.innerHTML = '';
- document.getElementById('bwtest-sample-count').innerText = '0 samples';
- setBwTestRunningUI(true);
- try {
- const res = await fetch(`${API_BASE}/tools/bwtest/start`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- target,
- port,
- direction,
- protocol,
- bandwidth_limit,
- packet_size,
- streams,
- duration
- })
- });
- if (!res.ok) {
- const err = await res.json();
- throw new Error(err.error || 'Failed to start bandwidth test');
- }
- showToast('Benchmark Started', `Target: ${target}:${port} (${direction.toUpperCase()}, ${protocol.toUpperCase()})`, 'info');
- startBwTestTelemetry();
- } catch (err) {
- setBwTestRunningUI(false);
- showToast('Start Failed', err.message, 'error');
- }
- }
- function setBwTestRunningUI(running) {
- bwtestState.running = running;
- const startBtn = document.getElementById('bwtest-btn-start');
- const stopBtn = document.getElementById('bwtest-btn-stop');
- const badge = document.getElementById('bwtest-run-status-badge');
- const ph = document.getElementById('bwtest-chart-placeholder');
- if (running) {
- if (startBtn) {
- startBtn.disabled = true;
- startBtn.classList.add('opacity-50', 'cursor-not-allowed');
- }
- if (stopBtn) {
- stopBtn.disabled = false;
- stopBtn.classList.remove('opacity-40');
- }
- if (badge) {
- badge.innerText = 'TESTING...';
- badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-emerald-500/20 text-emerald-300 border border-emerald-500/40 font-bold animate-pulse';
- }
- if (ph) ph.style.display = 'none';
- } else {
- if (startBtn) {
- startBtn.disabled = false;
- startBtn.classList.remove('opacity-50', 'cursor-not-allowed');
- }
- if (stopBtn) {
- stopBtn.disabled = true;
- stopBtn.classList.add('opacity-40');
- }
- if (badge) {
- badge.innerText = 'IDLE';
- badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-slate-800 text-slate-400 border border-slate-700 font-semibold';
- }
- }
- }
- async function stopBwTest() {
- try {
- const res = await fetch(`${API_BASE}/tools/bwtest/stop`, { method: 'POST' });
- if (!res.ok) throw new Error(await responseError(res));
- showToast('Stop Requested', 'Waiting for the bandwidth test to finish', 'info');
- if (!bwtestState.pollTimer) startBwTestTelemetry();
- } catch (err) {
- showToast('Stop Failed', err.message, 'error');
- }
- }
- async function responseError(res) {
- const text = await res.text();
- try { const data = JSON.parse(text); return data.message || (typeof data.error === 'string' ? data.error : null) || `HTTP ${res.status}`; }
- catch { return text || `HTTP ${res.status}`; }
- }
- function processBwTestStatus(st) {
- if (st.session_id && bwtestState.sessionID !== st.session_id) {
- bwtestState.sessionID = st.session_id;
- bwtestState.lastSampleElapsed = -1;
- }
- for (const sample of st.recent_samples || []) {
- if (sample.elapsed_sec > (bwtestState.lastSampleElapsed ?? -1)) {
- handleBwTestSample(sample);
- bwtestState.lastSampleElapsed = sample.elapsed_sec;
- }
- }
- if (!st.running) {
- if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
- bwtestState.pollTimer = null;
- setBwTestRunningUI(false);
- handleBwTestFinish(st.summary, st.error);
- }
- }
- function startBwTestTelemetry() {
- if (!state.currentUser) return;
- if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
- let busy = false;
- const poll = async () => {
- if (busy || !state.currentUser || document.hidden) return;
- busy = true;
- try {
- const res = await fetch(`${API_BASE}/tools/bwtest/status`);
- if (!res.ok) throw new Error(await responseError(res));
- processBwTestStatus(await res.json());
- } catch (err) {
- console.error('BwTest polling error:', err);
- } finally { busy = false; }
- };
- bwtestState.pollTimer = setInterval(poll, 400);
- poll();
- }
- function handleBwTestSample(s) {
- if (!s) return;
- const payloadHint = document.getElementById('bwtest-effective-payload');
- if (payloadHint && s.packet_size) payloadHint.innerText = `Effective datagram: ${s.packet_size} bytes`;
- const txMbps = s.tx_mbps || 0;
- const rxMbps = s.rx_mbps || 0;
- if (txMbps > bwtestState.peakTx) bwtestState.peakTx = txMbps;
- if (rxMbps > bwtestState.peakRx) bwtestState.peakRx = rxMbps;
- // KPI updates
- const elTx = document.getElementById('bwtest-stat-tx-mbps');
- if (elTx) {
- elTx.innerText = txMbps.toFixed(2);
- elTx.title = `Confirmed by peer; locally offered: ${(s.offered_tx_mbps || 0).toFixed(2)} Mbps`;
- }
- const elTxPeak = document.getElementById('bwtest-stat-tx-peak');
- if (elTxPeak) elTxPeak.innerText = `${bwtestState.peakTx.toFixed(2)} Mbps`;
- const elTxPkts = document.getElementById('bwtest-stat-tx-pkts');
- if (elTxPkts) elTxPkts.innerText = s.tx_packets || 0;
- const elRx = document.getElementById('bwtest-stat-rx-mbps');
- if (elRx) elRx.innerText = rxMbps.toFixed(2);
- const elRxPeak = document.getElementById('bwtest-stat-rx-peak');
- if (elRxPeak) elRxPeak.innerText = `${bwtestState.peakRx.toFixed(2)} Mbps`;
- const elRxPkts = document.getElementById('bwtest-stat-rx-pkts');
- if (elRxPkts) elRxPkts.innerText = s.rx_packets || 0;
- const elLoss = document.getElementById('bwtest-stat-loss');
- if (elLoss) {
- elLoss.innerText = `${(s.loss_pct || 0).toFixed(1)}%`;
- elLoss.className = (s.loss_pct > 1.0) ? 'text-2xl font-bold text-rose-400' : 'text-2xl font-bold text-emerald-400';
- }
- const elLostPkts = document.getElementById('bwtest-stat-lost-pkts');
- if (elLostPkts) elLostPkts.innerText = s.lost_packets || 0;
- const elJitter = document.getElementById('bwtest-stat-jitter');
- if (elJitter) elJitter.innerText = `${(s.jitter_ms || 0).toFixed(2)} ms`;
- const elTime = document.getElementById('bwtest-stat-time');
- if (elTime) elTime.innerText = `${(s.elapsed_sec || 0).toFixed(1)}s`;
- const elData = document.getElementById('bwtest-stat-data');
- if (elData) elData.innerText = formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0));
- const elGraphRate = document.getElementById('bwtest-graph-rate');
- if (elGraphRate) elGraphRate.innerText = `TX: ${txMbps.toFixed(1)} Mbps • RX: ${rxMbps.toFixed(1)} Mbps`;
- // Append point to chart buffer
- bwtestState.chartPoints.push({
- elapsed: s.elapsed_sec || 0,
- tx: txMbps,
- rx: rxMbps
- });
- if (bwtestState.chartPoints.length > bwtestState.maxChartPoints) {
- bwtestState.chartPoints.shift();
- }
- drawBwTestChart();
- // Add row to breakdown table
- const tbody = document.getElementById('bwtest-samples-tbody');
- if (tbody) {
- const tr = document.createElement('tr');
- tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
- tr.innerHTML = `
- <td class="py-1.5 px-3 font-semibold text-white">${(s.elapsed_sec || 0).toFixed(1)}s</td>
- <td class="py-1.5 px-3 font-bold text-cyan-400">${txMbps.toFixed(2)} Mbps</td>
- <td class="py-1.5 px-3 font-bold text-purple-400">${rxMbps.toFixed(2)} Mbps</td>
- <td class="py-1.5 px-3 ${(s.loss_pct > 1.0) ? 'text-rose-400 font-bold' : 'text-emerald-400'}">${(s.loss_pct || 0).toFixed(1)}%</td>
- <td class="py-1.5 px-3 text-slate-300">${(s.jitter_ms || 0).toFixed(2)} ms</td>
- <td class="py-1.5 px-3 text-slate-400">${formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0))}</td>
- `;
- tbody.insertBefore(tr, tbody.firstChild);
- const countEl = document.getElementById('bwtest-sample-count');
- if (countEl) countEl.innerText = `${tbody.children.length} samples`;
- }
- }
- function handleBwTestFinish(summary, error) {
- const badge = document.getElementById('bwtest-run-status-badge');
- if (error) {
- showToast('Benchmark Error', error, 'error');
- if (badge) {
- badge.innerText = 'ERROR';
- badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-rose-500/20 text-rose-300 border border-rose-500/40 font-bold';
- }
- } else if (summary) {
- const avgTx = summary.avg_tx_mbps.toFixed(1);
- const avgRx = summary.avg_rx_mbps.toFixed(1);
- showToast('Benchmark Complete', `Average TX: ${avgTx} Mbps | RX: ${avgRx} Mbps (Loss: ${summary.avg_loss_pct.toFixed(1)}%)`, 'success');
- if (badge) {
- badge.innerText = 'COMPLETED';
- badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-emerald-500/20 text-emerald-300 border border-emerald-500/40 font-bold';
- }
- }
- loadBwTestHistory();
- fetchBwTestServerStatus();
- }
- function resizeBwTestCanvas() {
- const canvas = document.getElementById('bwtest-chart');
- if (!canvas || !canvas.parentElement) return;
- const rect = canvas.parentElement.getBoundingClientRect();
- const dpr = window.devicePixelRatio || 1;
- canvas.width = rect.width * dpr;
- canvas.height = rect.height * dpr;
- const ctx = canvas.getContext('2d');
- ctx.scale(dpr, dpr);
- drawBwTestChart();
- }
- window.addEventListener('resize', () => {
- if (state.activeTab === 'bwtest') resizeBwTestCanvas();
- });
- function drawBwTestChart() {
- const canvas = document.getElementById('bwtest-chart');
- if (!canvas) return;
- const ctx = canvas.getContext('2d');
- const dpr = window.devicePixelRatio || 1;
- const width = canvas.width / dpr;
- const height = canvas.height / dpr;
- ctx.clearRect(0, 0, width, height);
- const points = bwtestState.chartPoints;
- if (!points || points.length === 0) return;
- // Determine scale ceiling
- let maxRate = 10;
- for (const p of points) {
- if (p.tx > maxRate) maxRate = p.tx;
- if (p.rx > maxRate) maxRate = p.rx;
- }
- maxRate = Math.ceil(maxRate * 1.25); // 25% headroom
- const paddingLeft = 55;
- const paddingBottom = 24;
- const paddingTop = 12;
- const paddingRight = 16;
- const chartW = width - paddingLeft - paddingRight;
- const chartH = height - paddingTop - paddingBottom;
- // Grid Lines and Y-Axis labels
- ctx.strokeStyle = 'rgba(51, 65, 85, 0.4)';
- ctx.lineWidth = 1;
- ctx.fillStyle = '#94a3b8';
- ctx.font = '10px monospace';
- ctx.textAlign = 'right';
- const gridSteps = 4;
- for (let i = 0; i <= gridSteps; i++) {
- const val = (maxRate / gridSteps) * i;
- const y = paddingTop + chartH - (i / gridSteps) * chartH;
- ctx.beginPath();
- ctx.moveTo(paddingLeft, y);
- ctx.lineTo(width - paddingRight, y);
- ctx.stroke();
- ctx.fillText(`${Math.round(val)}M`, paddingLeft - 8, y + 3);
- }
- // Draw TX Line (Cyan #22d3ee)
- drawSeries(ctx, points, p => p.tx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#22d3ee', 'rgba(34, 211, 238, 0.15)');
- // Draw RX Line (Purple #a855f7)
- drawSeries(ctx, points, p => p.rx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#a855f7', 'rgba(168, 85, 247, 0.15)');
- }
- function drawSeries(ctx, points, valFn, maxVal, left, top, w, h, strokeColor, fillColor) {
- if (points.length < 2) return;
- const stepX = w / Math.max(points.length - 1, 1);
- // Gradient area fill
- const grad = ctx.createLinearGradient(0, top, 0, top + h);
- grad.addColorStop(0, fillColor);
- grad.addColorStop(1, 'rgba(0, 0, 0, 0)');
- ctx.beginPath();
- points.forEach((p, idx) => {
- const x = left + idx * stepX;
- const val = valFn(p);
- const y = top + h - (val / maxVal) * h;
- if (idx === 0) {
- ctx.moveTo(x, y);
- } else {
- ctx.lineTo(x, y);
- }
- });
- // Complete path for fill
- ctx.lineTo(left + (points.length - 1) * stepX, top + h);
- ctx.lineTo(left, top + h);
- ctx.closePath();
- ctx.fillStyle = grad;
- ctx.fill();
- // Draw line stroke
- ctx.beginPath();
- ctx.lineWidth = 2.5;
- ctx.strokeStyle = strokeColor;
- points.forEach((p, idx) => {
- const x = left + idx * stepX;
- const val = valFn(p);
- const y = top + h - (val / maxVal) * h;
- if (idx === 0) {
- ctx.moveTo(x, y);
- } else {
- ctx.lineTo(x, y);
- }
- });
- ctx.stroke();
- // Draw end point halo
- const lastP = points[points.length - 1];
- const lastX = left + (points.length - 1) * stepX;
- const lastY = top + h - (valFn(lastP) / maxVal) * h;
- ctx.fillStyle = strokeColor;
- ctx.beginPath();
- ctx.arc(lastX, lastY, 4, 0, 2 * Math.PI);
- ctx.fill();
- }
- async function loadBwTestHistory() {
- try {
- const res = await fetch(`${API_BASE}/tools/bwtest/history`);
- if (!res.ok) return;
- const list = await res.json();
- renderBwTestHistory(Array.isArray(list) ? list : []);
- } catch (err) {
- console.error('Failed to load BwTest history:', err);
- }
- }
- function renderBwTestHistory(list) {
- const tbody = document.getElementById('bwtest-history-tbody');
- if (!tbody) return;
- if (list.length === 0) {
- tbody.innerHTML = `<tr><td colspan="10" class="p-6 text-center text-slate-500 text-xs font-sans">No past benchmark runs recorded yet.</td></tr>`;
- return;
- }
- tbody.innerHTML = '';
- list.forEach(item => {
- const s = item.summary || {};
- const tr = document.createElement('tr');
- tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
- const dirBadge = item.direction === 'both'
- ? `<span class="px-1.5 py-0.5 rounded text-[10px] bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 uppercase font-semibold">Both</span>`
- : item.direction === 'tx'
- ? `<span class="px-1.5 py-0.5 rounded text-[10px] bg-cyan-500/20 text-cyan-300 border border-cyan-500/30 uppercase font-semibold">TX Only</span>`
- : `<span class="px-1.5 py-0.5 rounded text-[10px] bg-purple-500/20 text-purple-300 border border-purple-500/30 uppercase font-semibold">RX Only</span>`;
- const protoBadge = item.protocol === 'tcp'
- ? `<span class="px-1.5 py-0.5 rounded text-[10px] bg-blue-500/20 text-blue-300 border border-blue-500/30 font-semibold uppercase">TCP</span>`
- : `<span class="px-1.5 py-0.5 rounded text-[10px] bg-amber-500/20 text-amber-300 border border-amber-500/30 font-semibold uppercase">UDP</span>`;
- const dateStr = item.timestamp ? new Date(item.timestamp).toLocaleString() : '-';
- tr.innerHTML = `
- <td class="py-2.5 px-4 font-bold text-white font-mono text-[11px]">${escapeHtml(item.id || '-')}</td>
- <td class="py-2.5 px-4 text-emerald-400 font-mono font-medium">${escapeHtml(item.target || '-')}</td>
- <td class="py-2.5 px-4">${protoBadge}</td>
- <td class="py-2.5 px-4">${dirBadge}</td>
- <td class="py-2.5 px-4 text-slate-300">${(s.duration_sec || 0).toFixed(1)}s</td>
- <td class="py-2.5 px-4 font-bold text-cyan-400 font-mono">${(s.avg_tx_mbps || 0).toFixed(1)} / ${(s.peak_tx_mbps || 0).toFixed(1)} <span class="text-[10px] text-slate-400 font-normal">Mbps</span></td>
- <td class="py-2.5 px-4 font-bold text-purple-400 font-mono">${(s.avg_rx_mbps || 0).toFixed(1)} / ${(s.peak_rx_mbps || 0).toFixed(1)} <span class="text-[10px] text-slate-400 font-normal">Mbps</span></td>
- <td class="py-2.5 px-4 ${(s.avg_loss_pct > 1.0) ? 'text-rose-400 font-bold' : 'text-emerald-400'} font-mono">${(s.avg_loss_pct || 0).toFixed(1)}% <span class="text-[10px] text-slate-400 font-normal">(${s.total_lost_packets || 0})</span></td>
- <td class="py-2.5 px-4 text-slate-300 font-mono">${(s.avg_jitter_ms || 0).toFixed(2)} ms</td>
- <td class="py-2.5 px-4 text-slate-400 text-[11px] font-sans">${escapeHtml(dateStr)}</td>
- `;
- tbody.appendChild(tr);
- });
- }
- // ======================== SETTINGS & ROUTER DNS ========================
- state.settingsSubTab = 'dns';
- state.dnsSettings = null;
- state.dnsStaticRecords = [];
- state.dnsStatus = null;
- function switchSettingsSubTab(sub) {
- state.settingsSubTab = sub;
- const btnDns = document.getElementById('btn-settings-subtab-dns');
- const btnSys = document.getElementById('btn-settings-subtab-system');
- const btnBak = document.getElementById('btn-settings-subtab-backup');
- const tabDns = document.getElementById('settings-subtab-dns');
- const tabSys = document.getElementById('settings-subtab-system');
- const tabBak = document.getElementById('settings-subtab-backup');
- const activeClass = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-cyan-600 text-white transition flex items-center gap-1.5 cursor-pointer';
- const inactiveClass = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-slate-800 text-slate-300 hover:text-white transition flex items-center gap-1.5 cursor-pointer';
- if (btnDns) btnDns.className = inactiveClass;
- if (btnSys) btnSys.className = inactiveClass;
- if (btnBak) btnBak.className = inactiveClass;
- tabDns?.classList.add('hidden');
- tabSys?.classList.add('hidden');
- tabBak?.classList.add('hidden');
- if (sub === 'dns') {
- if (btnDns) btnDns.className = activeClass;
- tabDns?.classList.remove('hidden');
- loadDNSSettings();
- } else if (sub === 'system') {
- if (btnSys) btnSys.className = activeClass;
- tabSys?.classList.remove('hidden');
- loadSystemSettings();
- } else if (sub === 'backup') {
- if (btnBak) btnBak.className = activeClass;
- tabBak?.classList.remove('hidden');
- loadBackupList();
- }
- }
- async function loadSettingsData(showLoading = false) {
- if (state.settingsSubTab === 'system') {
- await loadSystemSettings();
- } else if (state.settingsSubTab === 'backup') {
- await loadBackupList();
- } else {
- await loadDNSSettings();
- }
- }
- async function loadDNSSettings() {
- try {
- const [settingsRes, staticRes, statusRes] = await Promise.all([
- fetch(`${API_BASE}/dns/settings`),
- fetch(`${API_BASE}/dns/static`),
- fetch(`${API_BASE}/dns/status`)
- ]);
- if (settingsRes.ok) {
- state.dnsSettings = await settingsRes.json();
- populateDNSSettingsForm(state.dnsSettings);
- }
- if (staticRes.ok) {
- state.dnsStaticRecords = await staticRes.json();
- renderStaticDNSList();
- }
- if (statusRes.ok) {
- state.dnsStatus = await statusRes.json();
- updateDNSStatusView(state.dnsStatus);
- }
- } catch (err) {
- console.error('Failed to load DNS settings:', err);
- }
- }
- function populateDNSSettingsForm(s) {
- if (!s) return;
- const dnsForm = document.getElementById('form-dns-settings');
- const isEditing = dnsForm && (dnsForm.contains(document.activeElement) || dnsForm.dataset.dirty === 'true');
- const dynamicEl = document.getElementById('dns-dynamic-servers-list');
- if (dynamicEl) {
- if (Array.isArray(s.dynamic_servers) && s.dynamic_servers.length > 0) {
- dynamicEl.innerHTML = s.dynamic_servers.map(d => `<span class="px-2 py-0.5 rounded bg-cyan-950 text-cyan-300 border border-cyan-800 font-mono">${escapeHtml(d)}</span>`).join(' ');
- } else {
- dynamicEl.innerText = 'None';
- }
- }
- // If user is actively typing or editing in the form, do not overwrite their inputs!
- if (isEditing) return;
- const serversInput = document.getElementById('dns-servers-input');
- if (serversInput) serversInput.value = (s.servers || []).join(', ');
- const cacheSizeInput = document.getElementById('dns-cache-size-input');
- if (cacheSizeInput) cacheSizeInput.value = s.cache_size || 2048;
- const domainInput = document.getElementById('dns-domain-input');
- if (domainInput) domainInput.value = s.domain || '';
- const allowRemoteInput = document.getElementById('dns-allow-remote-input');
- if (allowRemoteInput) allowRemoteInput.checked = s.allow_remote_requests !== false;
- }
- function updateDNSStatusView(st) {
- if (!st) return;
- const preview = document.getElementById('dns-resolv-preview');
- if (preview) preview.innerText = st.resolv_conf_content || '(empty)';
- const pillText = document.getElementById('dns-live-status-text');
- const pill = document.getElementById('dns-live-status-pill');
- if (pill && pillText) {
- if (st.service_running) {
- pill.className = 'px-2.5 py-1 rounded-full text-[11px] font-mono bg-emerald-500/10 text-emerald-400 border border-emerald-500/30 flex items-center gap-1.5';
- pillText.innerText = 'DNS Service Active';
- } else {
- pill.className = 'px-2.5 py-1 rounded-full text-[11px] font-mono bg-rose-500/10 text-rose-400 border border-rose-500/30 flex items-center gap-1.5';
- pillText.innerText = 'DNS Service Inactive';
- }
- }
- }
- function appendDNSPreset(preset) {
- const input = document.getElementById('dns-servers-input');
- if (!input) return;
- const dnsForm = document.getElementById('form-dns-settings');
- if (dnsForm) dnsForm.dataset.dirty = 'true';
- const current = input.value.trim();
- if (!current) {
- input.value = preset;
- } else {
- const existing = current.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
- const toAdd = preset.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
- toAdd.forEach(ip => {
- if (!existing.includes(ip)) existing.push(ip);
- });
- input.value = existing.join(', ');
- }
- }
- async function saveDNSSettings(e) {
- e.preventDefault();
- const rawServers = document.getElementById('dns-servers-input')?.value || '';
- const servers = rawServers.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
- if (servers.length === 0) {
- showToast('Validation Error', 'Please enter at least one upstream DNS server IP', 'error');
- return;
- }
- const cacheSize = parseInt(document.getElementById('dns-cache-size-input')?.value || '2048', 10);
- const domain = (document.getElementById('dns-domain-input')?.value || '').trim();
- const allowRemote = document.getElementById('dns-allow-remote-input')?.checked ?? true;
- try {
- const res = await fetch(`${API_BASE}/dns/settings`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- servers: servers,
- cache_size: cacheSize,
- domain: domain,
- allow_remote_requests: allowRemote
- })
- });
- const data = await res.json();
- if (res.ok) {
- const dnsForm = document.getElementById('form-dns-settings');
- if (dnsForm) dnsForm.dataset.dirty = 'false';
- showToast('DNS Applied', 'Router DNS forwarders and resolver settings updated successfully', 'success');
- loadDNSSettings();
- } else {
- showToast('Error', data.error || data.message || 'Failed to save DNS settings', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function flushDNSCache() {
- try {
- const res = await fetch(`${API_BASE}/dns/flush`, { method: 'POST' });
- if (res.ok) {
- showToast('Cache Flushed', 'Router DNS cache cleared and static hosts reloaded', 'success');
- loadDNSSettings();
- } else {
- const err = await res.json();
- showToast('Error', err.error || 'Failed to flush cache', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- function renderStaticDNSList() {
- const tbody = document.getElementById('dns-static-tbody');
- const empty = document.getElementById('dns-static-empty');
- const badge = document.getElementById('dns-static-count-badge');
- if (!tbody) return;
- tbody.innerHTML = '';
- const records = state.dnsStaticRecords || [];
- if (badge) badge.innerText = `${records.length} Records`;
- if (records.length === 0) {
- empty?.classList.remove('hidden');
- return;
- }
- empty?.classList.add('hidden');
- records.forEach(rec => {
- const tr = document.createElement('tr');
- tr.className = `hover:bg-slate-800/40 transition text-xs ${rec.disabled ? 'opacity-50' : ''}`;
- tr.innerHTML = `
- <td class="py-2.5 px-4 font-bold text-white">${escapeHtml(rec.name)}</td>
- <td class="py-2.5 px-4">
- <span class="px-2 py-0.5 rounded text-[10px] font-bold ${
- rec.type === 'CNAME' ? 'bg-purple-950 text-purple-300 border border-purple-800' :
- (rec.type === 'AAAA' ? 'bg-blue-950 text-blue-300 border border-blue-800' : 'bg-cyan-950 text-cyan-300 border border-cyan-800')
- }">
- ${rec.type || 'A'}
- </span>
- </td>
- <td class="py-2.5 px-4 text-emerald-400 font-mono">${escapeHtml(rec.address)}</td>
- <td class="py-2.5 px-4 text-slate-400 font-mono">${rec.ttl || 3600}s</td>
- <td class="py-2.5 px-4 text-slate-400 italic truncate max-w-[140px]">${escapeHtml(rec.comment || '-')}</td>
- <td class="py-2.5 px-4">
- <span class="px-1.5 py-0.5 rounded text-[10px] font-semibold ${rec.disabled ? 'bg-slate-800 text-slate-500' : 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30'}">
- ${rec.disabled ? 'Disabled' : 'Active'}
- </span>
- </td>
- <td class="py-2.5 px-4 text-right space-x-2 font-sans whitespace-nowrap">
- <button onclick="toggleStaticDNS('${rec.id}', ${!rec.disabled})" class="text-xs ${rec.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${rec.disabled ? 'Enable' : 'Disable'}</button>
- <button onclick="openStaticDNSModal('${rec.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
- <button onclick="deleteStaticDNS('${rec.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
- </td>
- `;
- tbody.appendChild(tr);
- });
- }
- function openStaticDNSModal(id = null) {
- const modal = document.getElementById('modal-static-dns');
- const title = document.getElementById('modal-static-dns-title');
- const form = document.getElementById('form-static-dns');
- if (!modal || !form) return;
- form.reset();
- document.getElementById('modal-static-dns-id').value = '';
- if (id) {
- const rec = (state.dnsStaticRecords || []).find(r => r.id === id);
- if (rec) {
- if (title) title.innerText = 'Edit Static DNS Record';
- document.getElementById('modal-static-dns-id').value = rec.id;
- document.getElementById('modal-static-dns-name').value = rec.name;
- document.getElementById('modal-static-dns-type').value = rec.type || 'A';
- document.getElementById('modal-static-dns-addr').value = rec.address;
- document.getElementById('modal-static-dns-ttl').value = rec.ttl || 3600;
- document.getElementById('modal-static-dns-comment').value = rec.comment || '';
- document.getElementById('modal-static-dns-disabled').checked = !!rec.disabled;
- }
- } else {
- if (title) title.innerText = 'Add Static DNS Record';
- }
- modal.classList.remove('hidden');
- }
- function closeStaticDNSModal() {
- document.getElementById('modal-static-dns')?.classList.add('hidden');
- }
- async function submitSaveStaticDNS(e) {
- e.preventDefault();
- const id = document.getElementById('modal-static-dns-id')?.value || '';
- const name = (document.getElementById('modal-static-dns-name')?.value || '').trim();
- const type = document.getElementById('modal-static-dns-type')?.value || 'A';
- const address = (document.getElementById('modal-static-dns-addr')?.value || '').trim();
- const ttl = parseInt(document.getElementById('modal-static-dns-ttl')?.value || '3600', 10);
- const comment = (document.getElementById('modal-static-dns-comment')?.value || '').trim();
- const disabled = document.getElementById('modal-static-dns-disabled')?.checked ?? false;
- if (!name || !address) {
- showToast('Validation Error', 'Name and Target Address are required', 'error');
- return;
- }
- try {
- const res = await fetch(`${API_BASE}/dns/static`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ id, name, type, address, ttl, comment, disabled })
- });
- const data = await res.json();
- if (res.ok) {
- showToast('Static DNS Saved', `Saved record ${name} -> ${address}`, 'success');
- closeStaticDNSModal();
- loadDNSSettings();
- } else {
- showToast('Error', data.error || data.message || 'Failed to save record', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deleteStaticDNS(id) {
- if (!confirm('Are you sure you want to delete this static DNS entry?')) return;
- try {
- const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}`, { method: 'DELETE' });
- if (res.ok) {
- showToast('Deleted', 'Static DNS record deleted', 'success');
- loadDNSSettings();
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function toggleStaticDNS(id, disabled) {
- try {
- const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}/state`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ disabled })
- });
- if (res.ok) {
- showToast('Updated', `Record ${disabled ? 'disabled' : 'enabled'}`, 'success');
- loadDNSSettings();
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function loadSystemSettings() {
- try {
- const sysForm = document.getElementById('form-system-settings');
- const isEditing = sysForm && (sysForm.contains(document.activeElement) || sysForm.dataset.dirty === 'true');
- const res = await fetch(`${API_BASE}/system/settings`);
- if (res.ok) {
- const data = await res.json();
- if (!isEditing) {
- const hostInput = document.getElementById('system-hostname-input');
- if (hostInput) hostInput.value = data.hostname || '';
- const tzInput = document.getElementById('system-timezone-input');
- if (tzInput && data.timezone) tzInput.value = data.timezone;
- }
- }
- } catch (err) {
- console.error('Failed to load system settings:', err);
- }
- }
- async function saveSystemSettings(e) {
- e.preventDefault();
- const hostname = (document.getElementById('system-hostname-input')?.value || '').trim();
- const timezone = document.getElementById('system-timezone-input')?.value || 'UTC';
- try {
- const res = await fetch(`${API_BASE}/system/settings`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ hostname, timezone })
- });
- const data = await res.json();
- if (res.ok) {
- const sysForm = document.getElementById('form-system-settings');
- if (sysForm) sysForm.dataset.dirty = 'false';
- showToast('System Updated', 'Hostname and timezone saved successfully', 'success');
- const sideH = document.getElementById('side-hostname');
- if (sideH) sideH.innerText = data.hostname;
- } else {
- showToast('Error', data.error || 'Failed to save system settings', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // =============================================================================
- // BACKUP & RESTORE MANAGER
- // =============================================================================
- state.selectedBackupFile = null;
- state.inspectedBackupManifest = null;
- state.pendingRestoreTarget = null;
- state.backupsList = [];
- async function exportBackupDownload() {
- const btn = document.getElementById('btn-export-backup');
- const commentInput = document.getElementById('backup-export-comment');
- const comment = (commentInput?.value || '').trim();
- const originalHtml = btn ? btn.innerHTML : '';
- if (btn) {
- btn.disabled = true;
- btn.innerHTML = `<span class="w-3.5 h-3.5 rounded-full border-2 border-white border-t-transparent animate-spin inline-block"></span> Generating Backup...`;
- }
- try {
- const res = await fetch(`${API_BASE}/system/backup/export?comment=${encodeURIComponent(comment)}`);
- if (!res.ok) {
- const err = await res.json().catch(() => ({}));
- showToast('Export Failed', err.message || 'Failed to generate backup archive', 'error');
- return;
- }
- const blob = await res.blob();
- const disposition = res.headers.get('Content-Disposition') || '';
- let filename = 'debtik-backup.zip';
- const match = disposition.match(/filename="?([^";]+)"?/);
- if (match && match[1]) {
- filename = match[1];
- }
- const blobUrl = window.URL.createObjectURL(blob);
- const a = document.createElement('a');
- a.href = blobUrl;
- a.download = filename;
- document.body.appendChild(a);
- a.click();
- setTimeout(() => {
- window.URL.revokeObjectURL(blobUrl);
- a.remove();
- }, 1000);
- showToast('Backup Created', `Full configuration archive saved as ${filename}`, 'success');
- } catch (err) {
- showToast('Export Error', err.message || 'Network error during download', 'error');
- } finally {
- if (btn) {
- btn.disabled = false;
- btn.innerHTML = originalHtml;
- }
- }
- }
- async function onBackupFileSelected(e) {
- const file = e.target.files?.[0];
- if (!file) return;
- const label = document.getElementById('backup-file-label');
- if (label) {
- label.innerText = `Selected: ${file.name} (${formatBytes(file.size)})`;
- }
- await inspectBackupFile(file);
- }
- async function inspectBackupFile(file) {
- const preview = document.getElementById('backup-inspect-preview');
- const restoreBtn = document.getElementById('btn-restore-backup');
- const formData = new FormData();
- formData.append('backup', file);
- try {
- const res = await fetch(`${API_BASE}/system/backup/inspect`, {
- method: 'POST',
- body: formData
- });
- const data = await res.json();
- if (!res.ok || !data.success || !data.manifest) {
- if (preview) preview.classList.add('hidden');
- if (restoreBtn) restoreBtn.disabled = true;
- showToast('Validation Error', data.message || 'Invalid or corrupted DebTik backup archive', 'error');
- return;
- }
- const mf = data.manifest;
- state.selectedBackupFile = file;
- state.inspectedBackupManifest = mf;
- const vEl = document.getElementById('backup-inspect-version');
- const hEl = document.getElementById('backup-inspect-hostname');
- const fEl = document.getElementById('backup-inspect-files');
- const dEl = document.getElementById('backup-inspect-date');
- const cEl = document.getElementById('backup-inspect-comment');
- if (vEl) vEl.innerText = `DebTik v${escapeHtml(mf.debtik_version || '1.0')}`;
- if (hEl) hEl.innerText = escapeHtml(mf.hostname || 'DebTik');
- if (fEl) fEl.innerText = `${mf.files?.length || 0} items`;
- if (dEl) dEl.innerText = mf.created_at ? new Date(mf.created_at).toLocaleString() : 'N/A';
- if (cEl) cEl.innerText = mf.comment ? `"${escapeHtml(mf.comment)}"` : '';
- if (preview) preview.classList.remove('hidden');
- if (restoreBtn) restoreBtn.disabled = false;
- } catch (err) {
- if (preview) preview.classList.add('hidden');
- if (restoreBtn) restoreBtn.disabled = true;
- showToast('Inspection Failed', err.message || 'Failed to inspect backup file', 'error');
- }
- }
- function confirmRestoreBackup(localFilename = null) {
- const modal = document.getElementById('modal-restore-confirm');
- const details = document.getElementById('modal-restore-details');
- const progress = document.getElementById('modal-restore-progress');
- const cancelBtn = document.getElementById('btn-cancel-restore');
- const execBtn = document.getElementById('btn-execute-restore');
- if (progress) progress.classList.add('hidden');
- if (cancelBtn) cancelBtn.disabled = false;
- if (execBtn) {
- execBtn.disabled = false;
- execBtn.innerText = 'Yes, Restore & Reload';
- }
- if (localFilename) {
- state.pendingRestoreTarget = { type: 'local', filename: localFilename };
- if (details) {
- details.innerHTML = `<div>Source: <span class="text-white font-bold">Local Safety Backup</span></div>
- <div>File: <span class="text-cyan-400 font-bold">${escapeHtml(localFilename)}</span></div>`;
- }
- } else {
- if (!state.selectedBackupFile || !state.inspectedBackupManifest) {
- showToast('Error', 'Please select a valid backup archive first', 'error');
- return;
- }
- state.pendingRestoreTarget = { type: 'file', file: state.selectedBackupFile };
- const mf = state.inspectedBackupManifest;
- if (details) {
- details.innerHTML = `<div>Archive: <span class="text-white font-bold">${escapeHtml(state.selectedBackupFile.name)}</span> (${formatBytes(state.selectedBackupFile.size)})</div>
- <div>Origin Hostname: <span class="text-cyan-400 font-bold">${escapeHtml(mf.hostname)}</span></div>
- <div>Created: <span class="text-slate-300">${mf.created_at ? new Date(mf.created_at).toLocaleString() : 'N/A'}</span></div>
- <div>Files: <span class="text-emerald-400">${mf.files?.length || 0} configuration files</span></div>`;
- }
- }
- if (modal) modal.classList.remove('hidden');
- }
- function closeRestoreModal() {
- const modal = document.getElementById('modal-restore-confirm');
- if (modal) modal.classList.add('hidden');
- }
- async function executeRestoreBackup() {
- const target = state.pendingRestoreTarget;
- if (!target) return;
- const progress = document.getElementById('modal-restore-progress');
- const progressText = document.getElementById('modal-restore-progress-text');
- const cancelBtn = document.getElementById('btn-cancel-restore');
- const execBtn = document.getElementById('btn-execute-restore');
- if (cancelBtn) cancelBtn.disabled = true;
- if (execBtn) execBtn.disabled = true;
- if (progress) progress.classList.remove('hidden');
- if (progressText) progressText.innerText = 'Restoring configuration files into appliance...';
- try {
- let res;
- if (target.type === 'file') {
- const formData = new FormData();
- formData.append('backup', target.file);
- res = await fetch(`${API_BASE}/system/backup/restore`, {
- method: 'POST',
- body: formData
- });
- } else {
- res = await fetch(`${API_BASE}/system/backups/${encodeURIComponent(target.filename)}/restore`, {
- method: 'POST'
- });
- }
- const data = await res.json();
- if (!res.ok || !data.success) {
- showToast('Restore Failed', data.message || 'Error occurred while restoring configuration', 'error');
- if (cancelBtn) cancelBtn.disabled = false;
- if (execBtn) execBtn.disabled = false;
- if (progress) progress.classList.add('hidden');
- return;
- }
- if (progressText) {
- progressText.innerText = 'Configuration applied! DebTik appliance is reloading services, reconnecting...';
- }
- pollAfterRestoreReconnect();
- } catch (err) {
- showToast('Restore Error', err.message || 'Network error during restore', 'error');
- if (cancelBtn) cancelBtn.disabled = false;
- if (execBtn) execBtn.disabled = false;
- if (progress) progress.classList.add('hidden');
- }
- }
- function pollAfterRestoreReconnect() {
- let attempts = 0;
- const maxAttempts = 25;
- const timer = setInterval(async () => {
- attempts++;
- try {
- const res = await fetch(`${API_BASE}/system/status`, { cache: 'no-store' });
- if (res.ok) {
- clearInterval(timer);
- closeRestoreModal();
- showToast('Restoration Complete', 'DebTik configuration restored and appliance is back online!', 'success');
- setTimeout(() => {
- window.location.reload();
- }, 1200);
- }
- } catch (_) {
- // Still restarting, retry
- }
- if (attempts >= maxAttempts) {
- clearInterval(timer);
- closeRestoreModal();
- showToast('Reload Notice', 'Restore applied. Please refresh your browser to re-authenticate.', 'info');
- }
- }, 1500);
- }
- async function loadBackupList() {
- const tbody = document.getElementById('backups-table-tbody');
- const empty = document.getElementById('backups-empty-state');
- if (!tbody) return;
- try {
- const res = await fetch(`${API_BASE}/system/backups`);
- if (!res.ok) return;
- const list = await res.json();
- state.backupsList = list || [];
- renderBackupsTable(state.backupsList);
- } catch (err) {
- console.error('Failed to load backup list:', err);
- }
- }
- function renderBackupsTable(backups) {
- const tbody = document.getElementById('backups-table-tbody');
- const empty = document.getElementById('backups-empty-state');
- if (!tbody) return;
- if (!backups || backups.length === 0) {
- tbody.innerHTML = '';
- if (empty) empty.classList.remove('hidden');
- return;
- }
- if (empty) empty.classList.add('hidden');
- tbody.innerHTML = backups.map(bk => {
- const isAuto = bk.filename && bk.filename.startsWith('pre-restore-');
- const badge = isAuto
- ? `<span class="px-2 py-0.5 rounded text-[9px] font-mono bg-amber-500/10 text-amber-300 border border-amber-500/20">PRE-RESTORE</span>`
- : `<span class="px-2 py-0.5 rounded text-[9px] font-mono bg-cyan-500/10 text-cyan-300 border border-cyan-500/20">MANUAL</span>`;
- const dateStr = bk.mod_time ? new Date(bk.mod_time).toLocaleString() : 'N/A';
- return `<tr class="hover:bg-slate-800/40 transition">
- <td class="py-3 px-4 font-bold text-white flex items-center gap-2">
- ${badge}
- <span>${escapeHtml(bk.filename)}</span>
- </td>
- <td class="py-3 px-4 text-slate-300">${escapeHtml(bk.debtik_version || '1.0')}</td>
- <td class="py-3 px-4 text-cyan-400 font-bold">${escapeHtml(bk.hostname || 'DebTik')}</td>
- <td class="py-3 px-4 text-slate-400">${dateStr}</td>
- <td class="py-3 px-4 text-slate-300">${formatBytes(bk.size)}</td>
- <td class="py-3 px-4 text-slate-400 italic">${escapeHtml(bk.comment || '—')}</td>
- <td class="py-3 px-4 text-right space-x-2">
- <button type="button" onclick="downloadLocalBackup('${escapeHtml(bk.filename)}')"
- class="px-2.5 py-1 rounded-lg text-[11px] font-semibold bg-slate-800 hover:bg-slate-700 text-cyan-400 border border-slate-700 transition cursor-pointer">
- Download
- </button>
- <button type="button" onclick="confirmRestoreBackup('${escapeHtml(bk.filename)}')"
- class="px-2.5 py-1 rounded-lg text-[11px] font-semibold bg-amber-600/20 hover:bg-amber-600/30 text-amber-300 border border-amber-500/30 transition cursor-pointer">
- Restore
- </button>
- </td>
- </tr>`;
- }).join('');
- }
- async function downloadLocalBackup(filename) {
- try {
- const res = await fetch(`${API_BASE}/system/backups/${encodeURIComponent(filename)}`);
- if (!res.ok) {
- showToast('Download Error', 'Failed to retrieve backup file', 'error');
- return;
- }
- const blob = await res.blob();
- const blobUrl = window.URL.createObjectURL(blob);
- const a = document.createElement('a');
- a.href = blobUrl;
- a.download = filename;
- document.body.appendChild(a);
- a.click();
- setTimeout(() => {
- window.URL.revokeObjectURL(blobUrl);
- a.remove();
- }, 1000);
- } catch (err) {
- showToast('Download Error', err.message, 'error');
- }
- }
- // =============================================================================
- // AUTHENTICATION & USER MANAGER
- // =============================================================================
- async function checkAuthStatus() {
- try {
- const res = await originalFetch(`${API_BASE}/auth/me`, {
- headers: {
- 'Authorization': `Bearer ${localStorage.getItem('debtik_token') || ''}`
- }
- });
- if (res.ok) {
- const user = await res.json();
- state.currentUser = user;
- updateUserProfileHeader(user);
- hideLoginScreen();
- state.isPolling = true;
- fetchData();
- initLiveTrafficStream();
- return true;
- } else {
- showLoginScreen(false);
- return false;
- }
- } catch (err) {
- showLoginScreen(false);
- return false;
- }
- }
- function showLoginScreen(isExpired = false) {
- const el = document.getElementById('login-screen');
- if (el) el.classList.remove('hidden');
- const errEl = document.getElementById('login-error');
- const errTxt = document.getElementById('login-error-text');
- if (isExpired && errEl && errTxt) {
- errTxt.innerText = 'Session expired. Please sign in again.';
- errEl.classList.remove('hidden');
- } else if (errEl) {
- errEl.classList.add('hidden');
- }
- const pwInput = document.getElementById('login-password');
- if (pwInput) pwInput.value = '';
- const userInput = document.getElementById('login-username');
- if (userInput && !userInput.value) userInput.focus();
- else if (pwInput) pwInput.focus();
- }
- function hideLoginScreen() {
- const el = document.getElementById('login-screen');
- if (el) el.classList.add('hidden');
- const errEl = document.getElementById('login-error');
- if (errEl) errEl.classList.add('hidden');
- }
- async function handleLoginSubmit(event) {
- event.preventDefault();
- const username = (document.getElementById('login-username')?.value || '').trim();
- const password = document.getElementById('login-password')?.value || '';
- const errEl = document.getElementById('login-error');
- const errTxt = document.getElementById('login-error-text');
- const btn = document.getElementById('login-submit-btn');
- const btnText = document.getElementById('login-btn-text');
- const spinner = document.getElementById('login-btn-spinner');
- if (!username || !password) {
- if (errTxt) errTxt.innerText = 'Username and password are required.';
- if (errEl) errEl.classList.remove('hidden');
- return;
- }
- if (errEl) errEl.classList.add('hidden');
- if (btn) btn.disabled = true;
- if (btnText) btnText.innerText = 'Authenticating...';
- if (spinner) spinner.classList.remove('hidden');
- try {
- const res = await originalFetch(`${API_BASE}/auth/login`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ username, password })
- });
- const data = await res.json();
- if (res.ok && data.success) {
- localStorage.setItem('debtik_token', data.token);
- state.currentUser = data.user;
- updateUserProfileHeader(data.user);
- hideLoginScreen();
- state.isPolling = true;
- showToast('Authenticated', `Signed in as ${data.user.username}`, 'success');
- const hash = window.location.hash.replace('#', '') || 'dashboard';
- navigate(hash);
- fetchData();
- initLiveTrafficStream();
- // Ensure background telemetry polling is active
- if (!window._telemetryInterval) {
- window._telemetryInterval = setInterval(() => {
- if (state.isPolling && state.currentUser && !document.hidden) {
- fetchData(false);
- }
- }, 5000);
- }
- } else {
- if (errTxt) errTxt.innerText = data.message || 'Invalid username or password';
- if (errEl) errEl.classList.remove('hidden');
- }
- } catch (err) {
- if (errTxt) errTxt.innerText = err.message || 'Failed to connect to router';
- if (errEl) errEl.classList.remove('hidden');
- } finally {
- if (btn) btn.disabled = false;
- if (btnText) btnText.innerText = 'Sign In to Controller';
- if (spinner) spinner.classList.add('hidden');
- }
- }
- async function handleLogoutClick() {
- try {
- await originalFetch(`${API_BASE}/auth/logout`, {
- method: 'POST',
- headers: {
- 'Authorization': `Bearer ${localStorage.getItem('debtik_token') || ''}`
- }
- });
- } catch (e) {}
- stopSessionPolling();
- localStorage.removeItem('debtik_token');
- state.currentUser = null;
- state.isPolling = false;
- if (window._telemetryInterval) {
- clearInterval(window._telemetryInterval);
- window._telemetryInterval = null;
- }
- if (trafficEventSource) {
- trafficEventSource.close();
- trafficEventSource = null;
- }
- if (trafficPollFallback) {
- clearInterval(trafficPollFallback);
- trafficPollFallback = null;
- }
- showLoginScreen(false);
- showToast('Signed Out', 'You have been signed out successfully', 'info');
- }
- function togglePasswordVisibility(id) {
- const input = document.getElementById(id);
- if (!input) return;
- input.type = input.type === 'password' ? 'text' : 'password';
- }
- function toggleUserMenu() {
- const menu = document.getElementById('user-menu-dropdown');
- if (menu) menu.classList.toggle('hidden');
- }
- function closeUserMenu() {
- const menu = document.getElementById('user-menu-dropdown');
- if (menu) menu.classList.add('hidden');
- }
- // Close user menu on outside click
- document.addEventListener('click', (e) => {
- const menu = document.getElementById('user-menu-dropdown');
- if (!menu || menu.classList.contains('hidden')) return;
- if (!e.target.closest('#user-menu-dropdown') && !e.target.closest('button[onclick*="toggleUserMenu"]')) {
- menu.classList.add('hidden');
- }
- });
- function updateUserProfileHeader(user) {
- if (!user) return;
- const navName = document.getElementById('nav-user-name');
- if (navName) navName.innerText = user.username;
- const dropName = document.getElementById('dropdown-user-name');
- if (dropName) dropName.innerText = user.username;
- const navRole = document.getElementById('nav-user-role');
- if (navRole) navRole.innerText = (user.role || 'read').toUpperCase();
- const navAvatar = document.getElementById('nav-user-avatar');
- if (navAvatar) {
- const initials = (user.username || 'AD').slice(0, 2).toUpperCase();
- navAvatar.innerText = initials;
- }
- const statCurUser = document.getElementById('stat-current-user');
- if (statCurUser) statCurUser.innerText = user.username;
- const statCurRole = document.getElementById('stat-current-role');
- if (statCurRole) statCurRole.innerText = (user.role || 'read').toUpperCase();
- // Role permissions UI visibility: hide user management for non-admins
- const isFullAdmin = user.role === 'full';
- const navUsers = document.getElementById('nav-users');
- if (navUsers) {
- if (isFullAdmin) navUsers.classList.remove('hidden');
- else navUsers.classList.add('hidden');
- }
- const dropdownUsers = document.getElementById('dropdown-item-users');
- if (dropdownUsers) {
- if (isFullAdmin) dropdownUsers.classList.remove('hidden');
- else dropdownUsers.classList.add('hidden');
- }
- }
- // ================= User Management CRUD =================
- async function loadUsers(isManual = false) {
- try {
- const res = await fetch(`${API_BASE}/users`);
- if (res.status === 403) {
- const tbody = document.getElementById('users-table-tbody');
- if (tbody) {
- tbody.innerHTML = `
- <tr>
- <td colspan="6" class="p-6 text-center text-amber-400 font-sans">
- <div class="inline-flex items-center gap-2">
- <svg class="w-5 h-5 text-amber-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"/></svg>
- <span>Viewing and managing users requires Super Administrator (full) permissions.</span>
- </div>
- </td>
- </tr>
- `;
- }
- return;
- }
- if (res.ok) {
- state.users = await res.json();
- renderUsersTable();
- const totalUsers = document.getElementById('stat-total-users');
- if (totalUsers) totalUsers.innerText = state.users.length;
- const adminCount = state.users.filter(u => u.role === 'full' && !u.disabled).length;
- const adminUsers = document.getElementById('stat-admin-users');
- if (adminUsers) adminUsers.innerText = adminCount;
- const badgeCount = document.getElementById('badge-users-count');
- if (badgeCount) badgeCount.innerText = state.users.length;
- if (isManual) showToast('Refreshed', 'User list updated', 'info');
- }
- } catch (err) {
- console.error('Failed to load users:', err);
- }
- }
- function renderUsersTable() {
- const tbody = document.getElementById('users-table-tbody');
- const emptyState = document.getElementById('users-empty-state');
- if (!tbody) return;
- tbody.innerHTML = '';
- const query = (document.getElementById('users-search-input')?.value || '').trim().toLowerCase();
- const filtered = (state.users || []).filter(u => {
- if (!query) return true;
- return u.username.toLowerCase().includes(query) ||
- (u.role || '').toLowerCase().includes(query) ||
- (u.comment || '').toLowerCase().includes(query);
- });
- if (filtered.length === 0) {
- if (emptyState) emptyState.classList.remove('hidden');
- return;
- }
- if (emptyState) emptyState.classList.add('hidden');
- const currentAuthUser = state.currentUser?.username || '';
- filtered.forEach(u => {
- const isSelf = u.username === currentAuthUser;
- const isFull = u.role === 'full';
- const isWrite = u.role === 'write';
- let roleBadge = `<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-300 border border-slate-700">READ (OBSERVER)</span>`;
- if (isFull) {
- roleBadge = `<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-purple-500/15 text-purple-300 border border-purple-500/30">FULL (SUPER ADMIN)</span>`;
- } else if (isWrite) {
- roleBadge = `<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-sky-500/15 text-sky-300 border border-sky-500/30">WRITE (OPERATOR)</span>`;
- }
- const statusBadge = u.disabled
- ? `<span class="inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-[10px] font-semibold bg-rose-500/15 text-rose-300 border border-rose-500/30"><span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>Disabled</span>`
- : `<span class="inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-[10px] font-semibold bg-emerald-500/15 text-emerald-300 border border-emerald-500/30"><span class="w-1.5 h-1.5 rounded-full bg-emerald-400"></span>Active</span>`;
- let lastLoginText = 'Never';
- if (u.last_login_at && !u.last_login_at.startsWith('0001-01-01')) {
- const dt = new Date(u.last_login_at);
- lastLoginText = dt.toLocaleString();
- }
- const initials = u.username.slice(0, 2).toUpperCase();
- const tr = document.createElement('tr');
- tr.className = 'hover:bg-slate-800/40 transition group';
- tr.innerHTML = `
- <td class="py-3 px-4">
- <div class="flex items-center gap-3">
- <div class="w-8 h-8 rounded-xl bg-slate-800 border border-slate-700/80 flex items-center justify-center font-bold text-xs text-white">
- ${initials}
- </div>
- <div>
- <div class="font-bold text-white text-xs flex items-center gap-2">
- <span>${escapeHtml(u.username)}</span>
- ${isSelf ? '<span class="text-[9px] bg-brand-500/20 text-brand-300 border border-brand-500/30 px-1.5 py-0.2 rounded font-mono">YOU</span>' : ''}
- </div>
- <div class="text-[10px] text-slate-500 font-sans">Created: ${u.created_at ? new Date(u.created_at).toLocaleDateString() : '-'}</div>
- </div>
- </div>
- </td>
- <td class="py-3 px-4 font-sans">
- ${roleBadge}
- </td>
- <td class="py-3 px-4 font-sans">
- ${statusBadge}
- </td>
- <td class="py-3 px-4 text-slate-300 font-sans text-xs">
- ${escapeHtml(u.comment) || '<span class="text-slate-600">-</span>'}
- </td>
- <td class="py-3 px-4 text-slate-400 text-xs">
- ${lastLoginText}
- </td>
- <td class="py-3 px-4 text-right space-x-1.5 font-sans">
- <button onclick="openAdminResetPasswordModal('${escapeHtml(u.username)}')"
- class="p-1.5 rounded-lg text-slate-400 hover:text-amber-400 hover:bg-slate-800 transition" title="Reset User Password">
- <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 7a2 2 0 012 2m4 0a6 6 0 01-7.743 5.743L11 17H9v2H7v2H4a1 1 0 01-1-1v-2.586a1 1 0 01.293-.707l5.964-5.964A6 6 0 1121 9z"/></svg>
- </button>
- <button onclick="openEditUserModal('${escapeHtml(u.username)}')"
- class="p-1.5 rounded-lg text-slate-400 hover:text-cyan-400 hover:bg-slate-800 transition" title="Edit User">
- <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/></svg>
- </button>
- ${!isSelf ? `
- <button onclick="deleteUser('${escapeHtml(u.username)}')"
- class="p-1.5 rounded-lg text-slate-400 hover:text-rose-400 hover:bg-slate-800 transition" title="Delete User">
- <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
- </button>
- ` : ''}
- </td>
- `;
- tbody.appendChild(tr);
- });
- }
- function openAddUserModal() {
- document.getElementById('user-add-username').value = '';
- document.getElementById('user-add-password').value = '';
- document.getElementById('user-add-confirm').value = '';
- document.getElementById('user-add-role').value = 'full';
- document.getElementById('user-add-comment').value = '';
- document.getElementById('modal-add-user')?.classList.remove('hidden');
- document.getElementById('user-add-username')?.focus();
- }
- function closeAddUserModal() {
- document.getElementById('modal-add-user')?.classList.add('hidden');
- }
- async function submitAddUser(event) {
- event.preventDefault();
- const username = (document.getElementById('user-add-username')?.value || '').trim();
- const password = document.getElementById('user-add-password')?.value || '';
- const confirm = document.getElementById('user-add-confirm')?.value || '';
- const role = document.getElementById('user-add-role')?.value || 'full';
- const comment = (document.getElementById('user-add-comment')?.value || '').trim();
- if (password !== confirm) {
- showToast('Validation Error', 'Passwords do not match', 'warning');
- return;
- }
- if (password.length < 4) {
- showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
- return;
- }
- try {
- const res = await fetch(`${API_BASE}/users`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ username, password, role, comment })
- });
- const data = await res.json();
- if (res.ok) {
- showToast('User Created', `Created user ${username} with ${role.toUpperCase()} permissions`, 'success');
- closeAddUserModal();
- loadUsers(false);
- } else {
- showToast('Error', data.message || 'Failed to create user', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- function openEditUserModal(username) {
- const user = (state.users || []).find(u => u.username === username);
- if (!user) return;
- document.getElementById('user-edit-username').value = user.username;
- document.getElementById('user-edit-username-title').innerText = `@${user.username}`;
- document.getElementById('user-edit-role').value = user.role || 'read';
- document.getElementById('user-edit-comment').value = user.comment || '';
- document.getElementById('user-edit-disabled').checked = !!user.disabled;
- document.getElementById('modal-edit-user')?.classList.remove('hidden');
- }
- function closeEditUserModal() {
- document.getElementById('modal-edit-user')?.classList.add('hidden');
- }
- async function submitEditUser(event) {
- event.preventDefault();
- const username = document.getElementById('user-edit-username')?.value;
- const role = document.getElementById('user-edit-role')?.value || 'read';
- const comment = (document.getElementById('user-edit-comment')?.value || '').trim();
- const disabled = document.getElementById('user-edit-disabled')?.checked || false;
- try {
- const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}`, {
- method: 'PUT',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ role, comment, disabled })
- });
- const data = await res.json();
- if (res.ok) {
- showToast('User Updated', `Updated settings for ${username}`, 'success');
- closeEditUserModal();
- loadUsers(false);
- // If updated own role/disabled status, refresh self profile
- if (username === state.currentUser?.username) {
- checkAuthStatus();
- }
- } else {
- showToast('Error', data.message || 'Failed to update user', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- function openAdminResetPasswordModal(username) {
- document.getElementById('admin-reset-username').value = username;
- document.getElementById('admin-reset-username-title').innerText = `@${username}`;
- document.getElementById('admin-reset-new-pw').value = '';
- document.getElementById('admin-reset-confirm-pw').value = '';
- document.getElementById('modal-admin-reset-pw')?.classList.remove('hidden');
- document.getElementById('admin-reset-new-pw')?.focus();
- }
- function closeAdminResetPasswordModal() {
- document.getElementById('modal-admin-reset-pw')?.classList.add('hidden');
- }
- async function submitAdminResetPassword(event) {
- event.preventDefault();
- const username = document.getElementById('admin-reset-username')?.value;
- const newPassword = document.getElementById('admin-reset-new-pw')?.value || '';
- const confirm = document.getElementById('admin-reset-confirm-pw')?.value || '';
- if (newPassword !== confirm) {
- showToast('Validation Error', 'Passwords do not match', 'warning');
- return;
- }
- if (newPassword.length < 4) {
- showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
- return;
- }
- try {
- const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}/password`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ new_password: newPassword })
- });
- const data = await res.json();
- if (res.ok) {
- showToast('Password Reset', `Password for user ${username} updated successfully`, 'success');
- closeAdminResetPasswordModal();
- } else {
- showToast('Error', data.message || 'Failed to reset password', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deleteUser(username) {
- if (username === state.currentUser?.username) {
- showToast('Action Forbidden', 'You cannot delete your own account', 'warning');
- return;
- }
- if (!confirm(`Are you sure you want to completely remove user "${username}"?`)) {
- return;
- }
- try {
- const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}`, {
- method: 'DELETE'
- });
- const data = await res.json();
- if (res.ok) {
- showToast('User Deleted', `User ${username} has been removed`, 'success');
- loadUsers(false);
- } else {
- showToast('Error', data.message || 'Failed to delete user', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- function openSelfPasswordModal() {
- document.getElementById('self-current-password').value = '';
- document.getElementById('self-new-password').value = '';
- document.getElementById('self-confirm-password').value = '';
- document.getElementById('modal-self-password')?.classList.remove('hidden');
- document.getElementById('self-current-password')?.focus();
- }
- function closeSelfPasswordModal() {
- document.getElementById('modal-self-password')?.classList.add('hidden');
- }
- async function submitSelfPassword(event) {
- event.preventDefault();
- const oldPassword = document.getElementById('self-current-password')?.value || '';
- const newPassword = document.getElementById('self-new-password')?.value || '';
- const confirm = document.getElementById('self-confirm-password')?.value || '';
- if (newPassword !== confirm) {
- showToast('Validation Error', 'New passwords do not match', 'warning');
- return;
- }
- if (newPassword.length < 4) {
- showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
- return;
- }
- try {
- const res = await fetch(`${API_BASE}/auth/change-password`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ old_password: oldPassword, new_password: newPassword })
- });
- const data = await res.json();
- if (res.ok) {
- showToast('Password Changed', 'Your password has been changed successfully', 'success');
- closeSelfPasswordModal();
- } else {
- showToast('Error', data.message || 'Failed to change password', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // ==================== MANAGEMENT SERVICES (/ip service) ====================
- state.services = [];
- async function loadServices(manual = false) {
- try {
- const res = await fetch(`${API_BASE}/system/services`);
- if (!res.ok) throw new Error('Failed to load services');
- const data = await res.json();
- state.services = data || [];
- renderServicesTable();
- updateCertificatesBadges();
- if (manual) showToast('Services Updated', 'Service status synchronized', 'success');
- } catch (err) {
- if (manual) showToast('Error', err.message, 'error');
- }
- }
- function renderServicesTable() {
- const tbody = document.getElementById('services-table-body');
- if (!tbody) return;
- if (!state.services || state.services.length === 0) {
- tbody.innerHTML = '<tr><td colspan="5" class="py-6 text-center text-slate-500 text-xs">No services configured.</td></tr>';
- return;
- }
- tbody.innerHTML = state.services.map(s => {
- const isOff = s.disabled;
- const statusBadge = isOff
- ? '<span class="px-2 py-0.5 rounded text-[10px] bg-rose-500/20 text-rose-300 border border-rose-500/30 font-bold uppercase">Disabled</span>'
- : '<span class="px-2 py-0.5 rounded text-[10px] bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 font-bold uppercase">Active</span>';
- const toggleBtn = isOff
- ? `<button onclick="toggleServiceState('${s.name}', false)" class="px-2.5 py-1 rounded-lg bg-emerald-500/20 text-emerald-300 hover:bg-emerald-500/30 border border-emerald-500/40 text-[11px] font-bold transition">Enable</button>`
- : `<button onclick="toggleServiceState('${s.name}', true)" class="px-2.5 py-1 rounded-lg bg-rose-500/20 text-rose-300 hover:bg-rose-500/30 border border-rose-500/40 text-[11px] font-bold transition">Disable</button>`;
- let certBadge = '';
- if (s.name === 'www-ssl') {
- if (s.certificate) {
- certBadge = `<span class="ml-2 inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-amber-300 border border-slate-700 font-mono">🔒 ${escapeHtml(s.certificate)}</span>`;
- } else {
- certBadge = `<span class="ml-2 inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] bg-rose-500/10 text-rose-400 border border-rose-500/20 font-mono">⚠️ No Cert Selected</span>`;
- }
- }
- const certArg = s.certificate ? `'${escapeHtml(s.certificate)}'` : "''";
- return `
- <tr class="hover:bg-slate-800/40 transition">
- <td class="py-3 px-4 font-bold text-white uppercase">${s.name} ${certBadge}</td>
- <td class="py-3 px-4">
- <div class="flex items-center gap-2">
- <span class="text-cyan-400 font-mono font-bold">${s.port}</span>
- <button onclick="openEditServiceModal('${s.name}', ${s.port}, ${s.disabled}, ${certArg})" title="Edit Service" class="text-slate-500 hover:text-cyan-400 p-1 rounded hover:bg-slate-800/80 transition">
- <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
- </button>
- </div>
- </td>
- <td class="py-3 px-4">${statusBadge}</td>
- <td class="py-3 px-4 text-slate-400 text-xs font-sans">${s.comment || '-'}</td>
- <td class="py-3 px-4 text-right">
- <div class="flex items-center justify-end gap-2">
- <button onclick="openEditServiceModal('${s.name}', ${s.port}, ${s.disabled}, ${certArg})" class="px-2.5 py-1 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-300 hover:text-white border border-slate-700 text-[11px] font-medium transition inline-flex items-center gap-1">
- <svg class="w-3.5 h-3.5 text-slate-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
- <span>Edit</span>
- </button>
- ${toggleBtn}
- </div>
- </td>
- </tr>
- `;
- }).join('');
- }
- function openEditServiceModal(serviceName, currentPort, isDisabled, currentCert = '') {
- document.getElementById('modal-service-name').value = serviceName;
- document.getElementById('modal-service-disabled').value = String(isDisabled);
- document.getElementById('modal-service-display-name').textContent = serviceName.toUpperCase();
- document.getElementById('modal-service-port').value = currentPort;
- const hintEl = document.getElementById('modal-service-port-hint');
- const warnEl = document.getElementById('modal-service-warning');
- const certGroup = document.getElementById('modal-service-cert-group');
- const certSelect = document.getElementById('modal-service-cert-select');
- if (serviceName === 'www') {
- hintEl.textContent = 'Default HTTP web port: 80';
- warnEl.classList.remove('hidden');
- certGroup.classList.add('hidden');
- } else if (serviceName === 'www-ssl') {
- hintEl.textContent = 'Default HTTPS web port: 443';
- warnEl.classList.remove('hidden');
- certGroup.classList.remove('hidden');
- const populateCertOptions = (certs) => {
- certSelect.innerHTML = '<option value="">-- No Certificate Selected --</option>';
- (certs || []).forEach(c => {
- const opt = document.createElement('option');
- opt.value = c.name;
- opt.textContent = `${c.name} (${c.common_name})${c.is_ca ? ' [CA]' : ''}`;
- if (c.name === currentCert) opt.selected = true;
- certSelect.appendChild(opt);
- });
- };
- if (state.certificates && state.certificates.length > 0) {
- populateCertOptions(state.certificates);
- } else {
- loadCertificates(false).then(() => {
- populateCertOptions(state.certificates);
- });
- }
- } else if (serviceName === 'telnet') {
- hintEl.textContent = 'Default Telnet console port: 8282';
- warnEl.classList.add('hidden');
- certGroup.classList.add('hidden');
- } else if (serviceName === 'ssh') {
- hintEl.textContent = 'Default SSH port: 2222';
- warnEl.classList.add('hidden');
- certGroup.classList.add('hidden');
- } else {
- hintEl.textContent = '';
- warnEl.classList.add('hidden');
- certGroup.classList.add('hidden');
- }
- const modal = document.getElementById('modal-service-edit');
- modal.classList.remove('hidden');
- setTimeout(() => document.getElementById('modal-service-port').focus(), 50);
- }
- function closeEditServiceModal() {
- const modal = document.getElementById('modal-service-edit');
- if (modal) modal.classList.add('hidden');
- }
- async function submitSaveServicePort(event) {
- event.preventDefault();
- const name = document.getElementById('modal-service-name').value;
- const disabled = document.getElementById('modal-service-disabled').value === 'true';
- const port = parseInt(document.getElementById('modal-service-port').value, 10);
- if (isNaN(port) || port < 1 || port > 65535) {
- showToast('Invalid Port', 'Port must be a valid number between 1 and 65535', 'error');
- return;
- }
- const certSelect = document.getElementById('modal-service-cert-select');
- const certVal = (name === 'www-ssl' && certSelect) ? certSelect.value : '';
- try {
- const res = await fetch(`${API_BASE}/system/services/${name}`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ port: port, disabled: disabled, certificate: certVal })
- });
- if (!res.ok) {
- const errData = await res.json();
- throw new Error(errData.message || 'Failed to update service settings');
- }
- closeEditServiceModal();
- showToast('Service Updated', `Service ${name.toUpperCase()} settings saved`, 'success');
- await loadServices();
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function toggleServiceState(serviceName, newDisabled) {
- if (serviceName === 'www' && newDisabled) {
- if (!confirm("WARNING: Disabling the Web service ('www') will turn off this Web UI and REST API. You will only be able to re-enable it via SSH (port 2222) or Telnet (port 8282) using 'ip service enable www'. Continue?")) {
- return;
- }
- }
- if (serviceName === 'www-ssl' && !newDisabled) {
- const sslSvc = (state.services || []).find(s => s.name === 'www-ssl');
- if (!sslSvc || !sslSvc.certificate) {
- showToast('Certificate Required', 'Please assign an SSL/TLS certificate to www-ssl before enabling HTTPS.', 'warning');
- openEditServiceModal('www-ssl', sslSvc ? sslSvc.port : 443, false, '');
- return;
- }
- }
- try {
- const res = await fetch(`${API_BASE}/system/services/${serviceName}/state`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ disabled: newDisabled })
- });
- if (!res.ok) {
- const errData = await res.json();
- throw new Error(errData.message || 'Failed to update service');
- }
- showToast('Service Updated', `Service ${serviceName} is now ${newDisabled ? 'disabled' : 'enabled'}`, 'success');
- await loadServices();
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // ==================== SYSTEM LOGS (/log) ====================
- state.logs = [];
- let logsTimer = null;
- async function loadLogs(manual = false) {
- const limitEl = document.getElementById('logs-limit-select');
- const limit = limitEl ? limitEl.value : '100';
- try {
- const res = await fetch(`${API_BASE}/system/logs?limit=${limit}`);
- if (!res.ok) throw new Error('Failed to load logs');
- const data = await res.json();
- state.logs = data.logs || [];
- renderLogsTable();
- if (manual) showToast('Logs Refreshed', `Fetched ${state.logs.length} log records`, 'success');
- } catch (err) {
- if (manual) showToast('Error', err.message, 'error');
- }
- // Setup auto-refresh if enabled and on logs tab
- if (!logsTimer && state.currentUser) {
- logsTimer = setInterval(() => {
- if (state.currentUser && !document.hidden && state.activeTab === 'logs') {
- const auto = document.getElementById('logs-auto-refresh');
- if (auto && auto.checked) {
- loadLogs(false);
- }
- }
- }, 3000);
- }
- }
- function renderLogsTable() {
- const tbody = document.getElementById('logs-table-body');
- if (!tbody) return;
- const search = (document.getElementById('logs-search-input')?.value || '').toLowerCase();
- const topicFilter = (document.getElementById('logs-topic-filter')?.value || '').toLowerCase();
- const filtered = state.logs.filter(entry => {
- if (topicFilter && !entry.topics.toLowerCase().includes(topicFilter)) {
- return false;
- }
- if (search && !entry.message.toLowerCase().includes(search) && !entry.topics.toLowerCase().includes(search)) {
- return false;
- }
- return true;
- });
- if (filtered.length === 0) {
- tbody.innerHTML = '<tr><td colspan="4" class="py-8 text-center text-slate-500 text-xs">No matching log entries found.</td></tr>';
- return;
- }
- tbody.innerHTML = filtered.map(l => {
- let topicColor = 'bg-slate-800 text-slate-300 border-slate-700';
- const topLower = l.topics.toLowerCase();
- if (topLower.includes('auth')) {
- topicColor = 'bg-amber-500/20 text-amber-300 border-amber-500/30';
- } else if (topLower.includes('dhcp')) {
- topicColor = 'bg-cyan-500/20 text-cyan-300 border-cyan-500/30';
- } else if (topLower.includes('route')) {
- topicColor = 'bg-blue-500/20 text-blue-300 border-blue-500/30';
- } else if (topLower.includes('firewall')) {
- topicColor = 'bg-rose-500/20 text-rose-300 border-rose-500/30';
- } else if (topLower.includes('error')) {
- topicColor = 'bg-red-500/20 text-red-300 border-red-500/30';
- } else if (topLower.includes('system')) {
- topicColor = 'bg-emerald-500/20 text-emerald-300 border-emerald-500/30';
- }
- const d = new Date(l.time);
- const timeStr = d.toLocaleDateString('en-US', { month: 'short', day: '2-digit' }) + ' ' + d.toLocaleTimeString('en-US', { hour12: false });
- return `
- <tr class="hover:bg-slate-800/40 transition">
- <td class="py-2 px-3 text-slate-500 font-mono">${l.id}</td>
- <td class="py-2 px-3 text-slate-400 font-mono whitespace-nowrap">${timeStr}</td>
- <td class="py-2 px-3 whitespace-nowrap">
- <span class="px-2 py-0.5 rounded text-[10px] font-bold border ${topicColor}">${l.topics}</span>
- </td>
- <td class="py-2 px-3 text-slate-200 font-mono break-all">${escapeHtml(l.message)}</td>
- </tr>
- `;
- }).join('');
- }
- // ==================== CERTIFICATES & SSL/TLS (/certificate) ====================
- state.certificates = [];
- async function loadCertificates(manual = false) {
- try {
- const res = await fetch(`${API_BASE}/certificates`);
- if (!res.ok) throw new Error('Failed to load certificates');
- state.certificates = await res.json() || [];
- updateCertificatesBadges();
- renderCertificatesTable();
- if (manual) showToast('Certificates Updated', `Loaded ${state.certificates.length} certificates`, 'success');
- } catch (err) {
- if (manual) showToast('Error', err.message, 'error');
- }
- }
- function updateCertificatesBadges() {
- const total = (state.certificates || []).length;
- const caCount = (state.certificates || []).filter(c => c.is_ca).length;
- const bCount = document.getElementById('badge-certs-count');
- if (bCount) bCount.innerText = total;
- const kpiTotal = document.getElementById('kpi-certs-total');
- if (kpiTotal) kpiTotal.innerText = total;
- const kpiCA = document.getElementById('kpi-certs-ca');
- if (kpiCA) kpiCA.innerText = caCount;
- const kpiHttps = document.getElementById('kpi-https-status');
- if (kpiHttps) {
- const sslSvc = (state.services || []).find(s => s.name === 'www-ssl');
- if (sslSvc) {
- if (!sslSvc.disabled) {
- kpiHttps.innerHTML = `<span class="text-emerald-400 font-bold">Enabled (Port ${sslSvc.port})</span><div class="text-[10px] text-slate-400 font-mono truncate">Cert: ${escapeHtml(sslSvc.certificate || 'None')}</div>`;
- } else {
- kpiHttps.innerHTML = `<span class="text-rose-400 font-bold">Disabled (Port ${sslSvc.port})</span><div class="text-[10px] text-slate-500 font-mono truncate">Cert: ${escapeHtml(sslSvc.certificate || 'None')}</div>`;
- }
- }
- }
- }
- function renderCertificatesTable() {
- const tbody = document.getElementById('certs-table-body');
- if (!tbody) return;
- if (!state.certificates || state.certificates.length === 0) {
- tbody.innerHTML = '<tr><td colspan="6" class="py-8 text-center text-slate-500 text-xs">No certificates configured yet. Click "Create CA" or "Issue Cert" to begin.</td></tr>';
- return;
- }
- tbody.innerHTML = state.certificates.map(c => {
- let typeBadge = '';
- if (c.is_ca) {
- typeBadge = '<span class="px-2 py-0.5 rounded text-[10px] bg-blue-500/20 text-blue-300 border border-blue-500/30 font-bold uppercase">🏛 CA</span>';
- } else if (c.type === 'acme') {
- typeBadge = '<span class="px-2 py-0.5 rounded text-[10px] bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 font-bold uppercase">🔒 Let\'s Encrypt</span>';
- } else if (c.issuer && c.issuer !== c.common_name) {
- typeBadge = '<span class="px-2 py-0.5 rounded text-[10px] bg-cyan-500/20 text-cyan-300 border border-cyan-500/30 font-bold uppercase">📜 Signed</span>';
- } else {
- typeBadge = '<span class="px-2 py-0.5 rounded text-[10px] bg-slate-700/60 text-slate-300 border border-slate-600 font-bold uppercase">📜 Self-Signed</span>';
- }
- const sansHtml = (c.sans && c.sans.length > 0)
- ? c.sans.map(s => `<span class="inline-block px-1.5 py-0.2 rounded text-[10px] bg-slate-800 text-slate-300 border border-slate-700 mr-1 mb-0.5">${escapeHtml(s)}</span>`).join('')
- : '<span class="text-slate-500">-</span>';
- const validTo = c.valid_to ? new Date(c.valid_to) : null;
- let validStr = '-';
- let validBadge = '';
- if (validTo && !isNaN(validTo.getTime())) {
- const now = new Date();
- const daysLeft = Math.round((validTo - now) / (1000 * 60 * 60 * 24));
- validStr = validTo.toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' });
- if (daysLeft < 0) {
- validBadge = '<span class="ml-1 text-[10px] text-rose-400 font-bold">(Expired)</span>';
- } else if (daysLeft < 30) {
- validBadge = `<span class="ml-1 text-[10px] text-amber-400 font-bold">(${daysLeft}d left)</span>`;
- } else {
- validBadge = `<span class="ml-1 text-[10px] text-slate-400">(${daysLeft}d left)</span>`;
- }
- }
- return `
- <tr class="hover:bg-slate-800/40 transition">
- <td class="py-3 px-4">${typeBadge}</td>
- <td class="py-3 px-4">
- <div class="font-bold text-white">${escapeHtml(c.name)}</div>
- <div class="text-[10px] text-slate-400 font-sans truncate max-w-xs" title="${escapeHtml(c.common_name)}">${escapeHtml(c.common_name)}</div>
- </td>
- <td class="py-3 px-4 text-slate-300 text-xs truncate max-w-xs" title="${escapeHtml(c.issuer || '-')}">${escapeHtml(c.issuer || '-')}</td>
- <td class="py-3 px-4 max-w-xs">${sansHtml}</td>
- <td class="py-3 px-4 whitespace-nowrap text-xs text-slate-300">
- <span>${validStr}</span> ${validBadge}
- ${c.type === 'acme' ? `<div class="text-[10px] ${c.renewal_error ? 'text-rose-400' : 'text-slate-400'}">${c.renewal_error ? 'Renewal failed: ' + escapeHtml(c.renewal_error) : 'Automatic renewal enabled'}</div>` : ''}
- <div class="text-[10px] text-slate-500">${c.key_type || ''}</div>
- </td>
- <td class="py-3 px-4 text-right whitespace-nowrap">
- <div class="flex items-center justify-end gap-1.5">
- <button onclick="openViewCertModal('${c.name}')" title="View & Export PEM" class="px-2.5 py-1 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-300 hover:text-white border border-slate-700 text-[11px] font-medium transition inline-flex items-center gap-1">
- <svg class="w-3.5 h-3.5 text-cyan-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/></svg>
- <span>View</span>
- </button>
- <button onclick="deleteCertificate('${c.name}')" title="Delete Certificate" class="px-2 py-1 rounded-lg bg-rose-500/10 hover:bg-rose-500/20 text-rose-400 border border-rose-500/30 text-[11px] transition">
- <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
- </button>
- </div>
- </td>
- </tr>
- `;
- }).join('');
- }
- // Create CA
- function openCreateCAModal() {
- document.getElementById('form-create-ca').reset();
- document.getElementById('ca-days').value = '3650';
- document.getElementById('ca-org').value = 'DebTik Network Appliance';
- document.getElementById('ca-country').value = 'GR';
- document.getElementById('ca-key-type').value = 'RSA-2048';
- document.getElementById('modal-create-ca').classList.remove('hidden');
- setTimeout(() => document.getElementById('ca-name').focus(), 50);
- }
- function closeCreateCAModal() {
- document.getElementById('modal-create-ca').classList.add('hidden');
- }
- async function submitCreateCA(event) {
- event.preventDefault();
- const payload = {
- name: document.getElementById('ca-name').value.trim(),
- common_name: document.getElementById('ca-cn').value.trim(),
- organization: document.getElementById('ca-org').value.trim(),
- country: document.getElementById('ca-country').value.trim(),
- days: parseInt(document.getElementById('ca-days').value, 10) || 3650,
- key_type: document.getElementById('ca-key-type').value
- };
- try {
- const res = await fetch(`${API_BASE}/certificates/ca`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(payload)
- });
- if (!res.ok) {
- const errData = await res.json();
- throw new Error(errData.message || 'Failed to create CA');
- }
- closeCreateCAModal();
- showToast('CA Created', `Root CA ${payload.name} generated successfully`, 'success');
- await loadCertificates();
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // Create Cert
- function openCreateCertModal() {
- document.getElementById('form-create-cert').reset();
- document.getElementById('cert-days').value = '730';
- document.getElementById('cert-key-type').value = 'RSA-2048';
- const caSelect = document.getElementById('cert-ca-select');
- caSelect.innerHTML = '<option value="">[ Self-Signed Certificate ]</option>';
- (state.certificates || []).filter(c => c.is_ca).forEach(ca => {
- const opt = document.createElement('option');
- opt.value = ca.name;
- opt.textContent = `${ca.name} (${ca.common_name})`;
- caSelect.appendChild(opt);
- });
- document.getElementById('modal-create-cert').classList.remove('hidden');
- setTimeout(() => document.getElementById('cert-name').focus(), 50);
- }
- function closeCreateCertModal() {
- document.getElementById('modal-create-cert').classList.add('hidden');
- }
- async function submitCreateCert(event) {
- event.preventDefault();
- const rawSans = document.getElementById('cert-sans').value;
- const sansList = rawSans ? rawSans.split(',').map(s => s.trim()).filter(Boolean) : [];
- const caName = document.getElementById('cert-ca-select').value;
- const payload = {
- name: document.getElementById('cert-name').value.trim(),
- common_name: document.getElementById('cert-cn').value.trim(),
- ca_name: caName,
- sans: sansList,
- days: parseInt(document.getElementById('cert-days').value, 10) || 730,
- key_type: document.getElementById('cert-key-type').value,
- is_server: true
- };
- try {
- const res = await fetch(`${API_BASE}/certificates/generate`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(payload)
- });
- if (!res.ok) {
- const errData = await res.json();
- throw new Error(errData.message || 'Failed to issue certificate');
- }
- closeCreateCertModal();
- showToast('Certificate Issued', `Certificate ${payload.name} generated successfully`, 'success');
- await loadCertificates();
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // Let's Encrypt
- function openLetsEncryptModal() {
- document.getElementById('form-letsencrypt').reset();
- document.getElementById('modal-letsencrypt').classList.remove('hidden');
- setTimeout(() => document.getElementById('le-domain').focus(), 50);
- }
- function closeLetsEncryptModal() {
- document.getElementById('modal-letsencrypt').classList.add('hidden');
- }
- async function submitLetsEncrypt(event) {
- event.preventDefault();
- const domain = document.getElementById('le-domain').value.trim();
- const email = document.getElementById('le-email').value.trim();
- let name = document.getElementById('le-name').value.trim();
- if (!name) name = domain.replace(/[^a-zA-Z0-9_-]/g, '-');
- const staging = document.getElementById('le-staging').checked;
- const btn = document.getElementById('btn-submit-letsencrypt');
- const origBtnHtml = btn.innerHTML;
- btn.disabled = true;
- btn.innerHTML = `<svg class="w-4 h-4 animate-spin text-white" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v8H4z"></path></svg> <span>Issuing (may take up to 60s)...</span>`;
- try {
- const res = await fetch(`${API_BASE}/certificates/letsencrypt`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- name: name,
- domain: domain,
- email: email,
- staging: staging
- })
- });
- if (!res.ok) {
- const errData = await res.json();
- throw new Error(errData.message || 'Let\'s Encrypt challenge failed');
- }
- closeLetsEncryptModal();
- showToast('Let\'s Encrypt Issued', `Successfully issued trusted certificate for ${domain}`, 'success');
- await loadCertificates();
- } catch (err) {
- showToast('Let\'s Encrypt Error', err.message, 'error');
- } finally {
- btn.disabled = false;
- btn.innerHTML = origBtnHtml;
- }
- }
- // Import Cert
- function openImportCertModal() {
- document.getElementById('form-import-cert').reset();
- document.getElementById('modal-import-cert').classList.remove('hidden');
- setTimeout(() => document.getElementById('import-cert-name').focus(), 50);
- }
- function closeImportCertModal() {
- document.getElementById('modal-import-cert').classList.add('hidden');
- }
- async function submitImportCert(event) {
- event.preventDefault();
- const payload = {
- name: document.getElementById('import-cert-name').value.trim(),
- cert_pem: document.getElementById('import-cert-pem').value.trim(),
- key_pem: document.getElementById('import-key-pem').value.trim()
- };
- try {
- const res = await fetch(`${API_BASE}/certificates/import`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(payload)
- });
- if (!res.ok) {
- const errData = await res.json();
- throw new Error(errData.message || 'Failed to import certificate');
- }
- closeImportCertModal();
- showToast('Certificate Imported', `Imported ${payload.name} successfully`, 'success');
- await loadCertificates();
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // View / Export Modal
- async function openViewCertModal(name) {
- const c = (state.certificates || []).find(x => x.name === name);
- if (!c) return;
- document.getElementById('view-cert-modal-title').textContent = `Certificate: ${c.name}`;
- document.getElementById('view-cert-cn').textContent = c.common_name || '-';
- document.getElementById('view-cert-issuer').textContent = c.issuer || '-';
- document.getElementById('view-cert-type').textContent = `${c.is_ca ? 'CA' : 'Server/Client'} (${c.key_type || 'Unknown'})`;
- document.getElementById('view-cert-validto').textContent = c.valid_to ? new Date(c.valid_to).toLocaleString() : '-';
- document.getElementById('view-cert-sans').textContent = (c.sans && c.sans.length > 0) ? c.sans.join(', ') : 'None';
- document.getElementById('view-cert-fp').textContent = c.fingerprint || '-';
- document.getElementById('view-cert-pem-text').value = 'Loading PEM...';
- document.getElementById('view-key-pem-text').value = 'Loading Key...';
- document.getElementById('modal-view-cert').classList.remove('hidden');
- try {
- const res = await fetch(`${API_BASE}/certificates/${encodeURIComponent(name)}/export`);
- if (!res.ok) throw new Error('Failed to export certificate PEM');
- const data = await res.json();
- document.getElementById('view-cert-pem-text').value = data.cert_pem || '';
- document.getElementById('view-key-pem-text').value = data.key_pem || '(Private key not available)';
- } catch (err) {
- document.getElementById('view-cert-pem-text').value = 'Error loading certificate PEM: ' + err.message;
- document.getElementById('view-key-pem-text').value = '';
- }
- }
- function closeViewCertModal() {
- document.getElementById('modal-view-cert').classList.add('hidden');
- }
- function copyCertPEM() {
- const text = document.getElementById('view-cert-pem-text').value;
- if (!text) return;
- navigator.clipboard.writeText(text).then(() => {
- showToast('Copied', 'Certificate PEM copied to clipboard', 'info');
- }).catch(() => {
- showToast('Error', 'Failed to copy to clipboard', 'error');
- });
- }
- function copyKeyPEM() {
- const text = document.getElementById('view-key-pem-text').value;
- if (!text) return;
- navigator.clipboard.writeText(text).then(() => {
- showToast('Copied', 'Private Key PEM copied to clipboard', 'info');
- }).catch(() => {
- showToast('Error', 'Failed to copy to clipboard', 'error');
- });
- }
- async function deleteCertificate(name) {
- if (!confirm(`Are you sure you want to delete certificate "${name}"? This action cannot be undone.`)) {
- return;
- }
- try {
- const res = await fetch(`${API_BASE}/certificates/${encodeURIComponent(name)}`, {
- method: 'DELETE'
- });
- if (!res.ok) {
- const errData = await res.json();
- throw new Error(errData.message || 'Failed to delete certificate');
- }
- showToast('Certificate Deleted', `Certificate "${name}" removed`, 'success');
- await loadCertificates();
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // Refresh immediately when returning to a backgrounded controller tab.
- document.addEventListener('visibilitychange', () => {
- if (!state.currentUser) return;
- if (document.hidden) {
- if (trafficEventSource) trafficEventSource.close();
- trafficEventSource = null;
- if (trafficPollFallback) clearInterval(trafficPollFallback);
- trafficPollFallback = null;
- } else {
- fetchData(false);
- initLiveTrafficStream();
- if (state.activeTab === 'bwtest') loadBwTestView();
- }
- });
- async function loadUpdateStatus(populate = true) {
- try {
- const res = await fetch(`${API_BASE}/update/status`);
- if (!res.ok) throw new Error(await responseError(res));
- const data = await res.json();
- if (populate && document.activeElement?.id !== 'update-repository') document.getElementById('update-repository').value = data.repository || '';
- if (populate && document.activeElement?.id !== 'update-tls-pin') document.getElementById('update-tls-pin').value = data.tls_key_pin || '';
- document.getElementById('update-installed').textContent = data.installed_version || 'unknown';
- document.getElementById('update-state').textContent = data.state || 'idle';
- document.getElementById('update-log').textContent = data.log || '';
- } catch (err) { showToast('Update Status', err.message, 'error'); }
- }
- async function saveUpdateConfig() {
- try {
- const repository = document.getElementById('update-repository').value.trim();
- const branch = 'master';
- const tls_key_pin = document.getElementById('update-tls-pin').value.trim();
- const res = await fetch(`${API_BASE}/update/config`, {method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({repository,branch,tls_key_pin})});
- if (!res.ok) throw new Error(await responseError(res));
- document.getElementById('update-install-button').disabled = true;
- document.getElementById('update-available').textContent = '—';
- showToast('Update Source Saved', 'Repository and branch saved', 'success');
- await loadUpdateStatus(false);
- } catch (err) { showToast('Update Source', err.message, 'error'); }
- }
- async function checkUpdate() {
- try {
- const res = await fetch(`${API_BASE}/update/check`, {method:'POST'});
- if (!res.ok) throw new Error(await responseError(res));
- const data = await res.json();
- document.getElementById('update-available').textContent = data.available_version;
- document.getElementById('update-install-button').disabled = !data.update_available;
- showToast('Git Check', data.update_available ? 'An update is available' : 'No newer version available', 'info');
- } catch (err) { showToast('Git Check Failed', err.message, 'error'); }
- }
- async function startUpdate(action) {
- if (!confirm(action === 'rollback' ? 'Restore the previous version and restart DebTik?' : 'Install the newer release version and restart DebTik?')) return;
- try {
- const res = await fetch(`${API_BASE}/update/${action}`, {method:'POST'});
- if (!res.ok) throw new Error(await responseError(res));
- showToast('Update Started', 'The service will restart; reconnect after a few seconds', 'info');
- await loadUpdateStatus(false);
- } catch (err) { showToast('Update Failed', err.message, 'error'); }
- }
- async function resetCurrentRuleCounters() { return resetFirewallRuleCounter('filter', resetRuleCounterDisplay); }
- async function resetCurrentNATRuleCounters() { return resetFirewallRuleCounter('nat', resetNATCounterDisplay); }
- async function resetCurrentMangleRuleCounters() { return resetFirewallRuleCounter('mangle', resetMangleCounterDisplay); }
- function safeFirewallRow(row) {
- const result = {...row};
- for (const [key,value] of Object.entries(result)) if (typeof value === 'string') result[key] = escapeHtml(value);
- result.id = encodeURIComponent(String(row.id || '')).replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29');
- return result;
- }
- function setFirewallDays(prefix, days) {
- const selected = days ? days.toLowerCase().split(',') : ['sun','mon','tue','wed','thu','fri','sat'];
- for (const d of ['sun','mon','tue','wed','thu','fri','sat']) { const el = document.getElementById(prefix+'-day-'+d); if (el) el.checked = selected.includes(d); }
- }
- function getFirewallDays(prefix) {
- if (document.getElementById(prefix+'-field-days')?.classList.contains('hidden')) return '';
- const selected = ['sun','mon','tue','wed','thu','fri','sat'].filter(d => document.getElementById(prefix+'-day-'+d)?.checked);
- if (!selected.length) throw new Error('Select at least one weekday, or remove the Days condition.');
- return selected.join(',');
- }
- async function resetFirewallRuleCounter(kind, resetDisplay) {
- const id = document.getElementById(kind+'-modal-id')?.value;
- if (!id) { resetDisplay(); return; }
- try {
- const response = await fetch(`${API_BASE}/firewall/${kind}/${encodeURIComponent(id)}/reset-counters`, {method:'POST'});
- if (!response.ok) { const error = await response.json(); throw new Error(error.message || 'Counter reset failed'); }
- resetDisplay(); await loadFirewall(false);
- } catch(error) { showToast('Error', error.message, 'error'); }
- }
- function reviewLegacyFirewallSettings(kind, id) {
- if (!id) return true;
- const rows = kind === 'filter' ? state.filterRules : kind === 'nat' ? state.natRules : state.mangleRules;
- const rule = (rows || []).find(r => r.id === id);
- if (!rule) return true;
- const unsupported = ['layer7_protocol','connection_bytes','connection_rate','pcc','in_bridge_port_list','out_bridge_port_list','tls_host','ingress_priority','priority','ipv4_options','dst_limit','psd','hotspot','route','sniff_target'];
- const present = unsupported.filter(key => rule[key]);
- if (!present.length) return true;
- return confirm('This saved rule contains unsupported settings: '+present.join(', ')+'. Saving removes them. Review the remaining match conditions before continuing.');
- }
- function refreshFirewallRejectTypes() {
- const select=document.getElementById('filter-modal-rejectwith'); if(!select) return;
- const old=select.value;
- const ipv6=document.getElementById('filter-modal-family')?.value==='6';
- const types=ipv6 ? ['icmp6-port-unreachable','icmp6-no-route','icmp6-adm-prohibited','icmp6-addr-unreachable','tcp-reset'] : ['icmp-port-unreachable','icmp-net-unreachable','icmp-host-unreachable','icmp-proto-unreachable','icmp-net-prohibited','icmp-host-prohibited','icmp-admin-prohibited','tcp-reset'];
- select.replaceChildren(...types.map(value=>{const option=document.createElement('option');option.value=value;option.textContent=value;return option}));
- if(types.includes(old))select.value=old;
- }
- function setFirewallActionSelection(kind, value) {
- const select=document.getElementById(kind+'-modal-action'); if(!select)return;
- if(!Array.from(select.options).some(option=>option.value===value)) {
- const option=document.createElement('option');option.value=value;option.textContent='Unsupported saved action: '+value;option.disabled=true;select.appendChild(option);
- }
- select.value=value;
- }
- // ==========================================
- // REVERSE PROXY & APPLICATION GATEWAY
- // ==========================================
- state.proxyRules = [];
- state.proxyConfig = null;
- async function loadReverseProxy(manual = false) {
- try {
- const [cfgRes, rulesRes, certsRes] = await Promise.all([
- fetch(`${API_BASE}/proxy/config`),
- fetch(`${API_BASE}/proxy/rules`),
- fetch(`${API_BASE}/certificates`).catch(() => null)
- ]);
- if (!cfgRes.ok) throw new Error('Failed to load proxy config');
- if (!rulesRes.ok) throw new Error('Failed to load proxy rules');
- state.proxyConfig = await cfgRes.json();
- state.proxyRules = await rulesRes.json() || [];
- if (certsRes && certsRes.ok) {
- state.certificates = await certsRes.json() || [];
- }
- renderProxyRules(state.proxyRules);
- updateProxyMetrics();
- if (manual) showToast('Reverse Proxy', 'Proxy configuration and rules reloaded', 'success');
- } catch (err) {
- console.error('loadReverseProxy error:', err);
- if (manual) showToast('Error', err.message, 'error');
- }
- }
- function updateProxyMetrics() {
- const badge = document.getElementById('badge-proxy-count');
- if (badge) badge.textContent = (state.proxyRules || []).length;
- const metricRules = document.getElementById('proxy-metric-rules');
- if (metricRules) metricRules.textContent = (state.proxyRules || []).length;
- const cfg = state.proxyConfig;
- const statusEl = document.getElementById('proxy-metric-status');
- const portsEl = document.getElementById('proxy-metric-ports');
- if (cfg) {
- if (statusEl) {
- if (cfg.enabled) {
- statusEl.innerHTML = '<span class="w-2.5 h-2.5 rounded-full bg-emerald-500 animate-pulse"></span><span class="text-white">Active</span>';
- } else {
- statusEl.innerHTML = '<span class="w-2.5 h-2.5 rounded-full bg-rose-500"></span><span class="text-rose-400">Disabled</span>';
- }
- }
- if (portsEl) {
- portsEl.textContent = `HTTP: ${cfg.http_port || 80} | HTTPS: ${cfg.https_port || 443}`;
- }
- }
- let totalRequests = 0;
- const certSet = new Set();
- (state.proxyRules || []).forEach(r => {
- totalRequests += (r.stats && r.stats.requests) || 0;
- if (r.enabled && r.certificate) certSet.add(r.certificate.toLowerCase());
- });
- const metricRequests = document.getElementById('proxy-metric-requests');
- if (metricRequests) metricRequests.textContent = totalRequests.toLocaleString();
- const metricCerts = document.getElementById('proxy-metric-certs');
- if (metricCerts) metricCerts.textContent = certSet.size;
- }
- function renderProxyRules(rules) {
- const tbody = document.getElementById('proxy-rules-table-body');
- if (!tbody) return;
- if (!rules || rules.length === 0) {
- tbody.innerHTML = '<tr><td colspan="9" class="py-8 text-center text-slate-500 text-xs font-sans">No reverse proxy rules configured yet. Click "Add Proxy Rule" to begin.</td></tr>';
- return;
- }
- tbody.innerHTML = rules.map(r => {
- const isEnabled = r.enabled !== false;
- const domainsStr = (r.domains && r.domains.length > 0) ? r.domains.map(d => `<span class="px-1.5 py-0.5 rounded bg-slate-800 text-slate-200 border border-slate-700 font-mono text-[11px]">${escapeHtml(d)}</span>`).join(' ') : '<span class="px-1.5 py-0.5 rounded bg-violet-950/60 text-violet-300 border border-violet-800/40 font-mono text-[11px]">* (any)</span>';
- const pathBadge = `<span class="px-2 py-0.5 rounded bg-cyan-950/60 text-cyan-300 border border-cyan-800/40 font-mono text-[11px] font-bold">${escapeHtml(r.path || '/')}</span>`;
- let protoBadge = '<span class="px-1.5 py-0.5 rounded bg-slate-800 text-slate-300 text-[10px] font-mono">HTTP/S</span>';
- if (r.protocol === 'https') protoBadge = '<span class="px-1.5 py-0.5 rounded bg-emerald-950 text-emerald-400 border border-emerald-800/40 text-[10px] font-mono font-bold">HTTPS</span>';
- else if (r.protocol === 'http') protoBadge = '<span class="px-1.5 py-0.5 rounded bg-sky-950 text-sky-400 border border-sky-800/40 text-[10px] font-mono">HTTP</span>';
- const certBadge = r.certificate ? `<span class="ml-1 text-[10px] bg-amber-950 text-amber-300 border border-amber-800/40 px-1 py-0.5 rounded font-mono truncate max-w-[120px] inline-block align-bottom" title="${escapeHtml(r.certificate)}">🔒 ${escapeHtml(r.certificate)}</span>` : '';
- const stripBadge = r.strip_path ? '<span class="text-amber-400 text-[11px]">Yes</span>' : '<span class="text-slate-500 text-[11px]">No</span>';
- const requests = (r.stats && r.stats.requests) ? r.stats.requests.toLocaleString() : '0';
- return `
- <tr class="hover:bg-slate-800/40 transition">
- <td class="py-3 px-4">
- <button onclick="toggleProxyRuleState('${escapeHtml(r.id)}', ${isEnabled})" class="relative inline-flex h-5 w-9 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none ${isEnabled ? 'bg-emerald-500' : 'bg-slate-700'}" title="${isEnabled ? 'Click to disable' : 'Click to enable'}">
- <span class="inline-block h-4 w-4 transform rounded-full bg-white shadow transition duration-200 ease-in-out ${isEnabled ? 'translate-x-4' : 'translate-x-0'}"></span>
- </button>
- </td>
- <td class="py-3 px-4">
- <div class="font-bold text-white text-xs">${escapeHtml(r.name || 'Unnamed Rule')}</div>
- ${r.comment ? `<div class="text-[10px] text-slate-400 font-sans truncate max-w-[200px]">${escapeHtml(r.comment)}</div>` : ''}
- </td>
- <td class="py-3 px-4 flex flex-wrap gap-1 items-center max-w-xs">
- ${domainsStr}
- </td>
- <td class="py-3 px-4">
- ${pathBadge}
- </td>
- <td class="py-3 px-4 font-mono text-slate-300 max-w-xs truncate" title="${escapeHtml(r.target_url || '')}">
- <span class="text-emerald-400">→</span> ${escapeHtml(r.target_url || '')}
- </td>
- <td class="py-3 px-4 whitespace-nowrap">
- ${protoBadge}${certBadge}
- </td>
- <td class="py-3 px-4 font-mono">
- ${stripBadge}
- </td>
- <td class="py-3 px-4 font-mono text-slate-300">
- ${requests}
- </td>
- <td class="py-3 px-4 text-right whitespace-nowrap">
- <button onclick="openEditProxyRuleModal('${escapeHtml(r.id)}')" class="px-2.5 py-1 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-300 text-xs mr-1 transition font-sans">Edit</button>
- <button onclick="deleteProxyRule('${escapeHtml(r.id)}')" class="px-2.5 py-1 rounded-lg bg-rose-950/40 hover:bg-rose-900/60 text-rose-300 border border-rose-800/40 text-xs transition font-sans">Delete</button>
- </td>
- </tr>
- `;
- }).join('');
- }
- function populateProxyCertDropdown(selectedVal = '') {
- const select = document.getElementById('proxy-rule-cert');
- if (!select) return;
- const certs = state.certificates || [];
- select.innerHTML = '<option value="">(None / Use Default Cert)</option>';
- certs.filter(c => !c.is_ca).forEach(c => {
- const opt = document.createElement('option');
- opt.value = c.name;
- const cn = c.common_name ? ` (${c.common_name})` : '';
- opt.textContent = `${c.name}${cn}`;
- if (selectedVal && selectedVal.toLowerCase() === c.name.toLowerCase()) {
- opt.selected = true;
- }
- select.appendChild(opt);
- });
- }
- function populateDefaultProxyCertDropdown(selectedVal = '') {
- const select = document.getElementById('proxy-cfg-default-cert');
- if (!select) return;
- const certs = state.certificates || [];
- select.innerHTML = '<option value="">(None / First Available Cert)</option>';
- certs.filter(c => !c.is_ca).forEach(c => {
- const opt = document.createElement('option');
- opt.value = c.name;
- const cn = c.common_name ? ` (${c.common_name})` : '';
- opt.textContent = `${c.name}${cn}`;
- if (selectedVal && selectedVal.toLowerCase() === c.name.toLowerCase()) {
- opt.selected = true;
- }
- select.appendChild(opt);
- });
- }
- function onProxyProtoChange() {
- const proto = document.getElementById('proxy-rule-proto')?.value;
- const certSelect = document.getElementById('proxy-rule-cert');
- const redirectCheck = document.getElementById('proxy-rule-http-to-https');
- if (proto === 'http') {
- if (certSelect) certSelect.disabled = true;
- if (redirectCheck) redirectCheck.disabled = true;
- } else {
- if (certSelect) certSelect.disabled = false;
- if (redirectCheck) redirectCheck.disabled = false;
- }
- }
- function openAddProxyRuleModal() {
- const modal = document.getElementById('modal-proxy-rule');
- if (!modal) return;
- document.getElementById('proxy-rule-modal-title').innerHTML = `
- <svg class="w-4 h-4 text-violet-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4" /></svg>
- <span>Add Reverse Proxy Rule</span>
- `;
- document.getElementById('proxy-rule-id').value = '';
- document.getElementById('proxy-rule-name').value = '';
- document.getElementById('proxy-rule-domains').value = '';
- document.getElementById('proxy-rule-path').value = '/';
- document.getElementById('proxy-rule-target').value = '';
- document.getElementById('proxy-rule-proto').value = 'both';
- document.getElementById('proxy-rule-strip-path').checked = false;
- document.getElementById('proxy-rule-http-to-https').checked = false;
- document.getElementById('proxy-rule-preserve-host').checked = false;
- document.getElementById('proxy-rule-insecure-tls').checked = false;
- document.getElementById('proxy-rule-enabled').checked = true;
- document.getElementById('proxy-rule-comment').value = '';
- populateProxyCertDropdown('');
- onProxyProtoChange();
- modal.classList.remove('hidden');
- }
- function openEditProxyRuleModal(id) {
- const modal = document.getElementById('modal-proxy-rule');
- if (!modal) return;
- const rule = (state.proxyRules || []).find(r => r.id === id);
- if (!rule) {
- showToast('Error', 'Rule not found', 'error');
- return;
- }
- document.getElementById('proxy-rule-modal-title').innerHTML = `
- <svg class="w-4 h-4 text-violet-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" /></svg>
- <span>Edit Reverse Proxy Rule</span>
- `;
- document.getElementById('proxy-rule-id').value = rule.id || '';
- document.getElementById('proxy-rule-name').value = rule.name || '';
- document.getElementById('proxy-rule-domains').value = (rule.domains || []).join(', ');
- document.getElementById('proxy-rule-path').value = rule.path || '/';
- document.getElementById('proxy-rule-target').value = rule.target_url || '';
- document.getElementById('proxy-rule-proto').value = rule.protocol || 'both';
- document.getElementById('proxy-rule-strip-path').checked = !!rule.strip_path;
- document.getElementById('proxy-rule-http-to-https').checked = !!rule.http_to_https;
- document.getElementById('proxy-rule-preserve-host').checked = !!rule.preserve_host;
- document.getElementById('proxy-rule-insecure-tls').checked = !!rule.insecure_tls;
- document.getElementById('proxy-rule-enabled').checked = rule.enabled !== false;
- document.getElementById('proxy-rule-comment').value = rule.comment || '';
- populateProxyCertDropdown(rule.certificate || '');
- onProxyProtoChange();
- modal.classList.remove('hidden');
- }
- function closeProxyRuleModal() {
- const modal = document.getElementById('modal-proxy-rule');
- if (modal) modal.classList.add('hidden');
- }
- async function saveProxyRule(event) {
- event.preventDefault();
- const id = document.getElementById('proxy-rule-id').value;
- const name = document.getElementById('proxy-rule-name').value.trim();
- const rawDomains = document.getElementById('proxy-rule-domains').value.trim();
- const pathVal = document.getElementById('proxy-rule-path').value.trim() || '/';
- const target = document.getElementById('proxy-rule-target').value.trim();
- const proto = document.getElementById('proxy-rule-proto').value;
- const cert = document.getElementById('proxy-rule-cert').value;
- const stripPath = document.getElementById('proxy-rule-strip-path').checked;
- const httpToHttps = document.getElementById('proxy-rule-http-to-https').checked;
- const preserveHost = document.getElementById('proxy-rule-preserve-host').checked;
- const insecureTLS = document.getElementById('proxy-rule-insecure-tls').checked;
- const enabled = document.getElementById('proxy-rule-enabled').checked;
- const comment = document.getElementById('proxy-rule-comment').value.trim();
- let domains = [];
- if (rawDomains && rawDomains !== '*') {
- domains = rawDomains.split(',').map(d => d.trim()).filter(d => d.length > 0);
- }
- const payload = {
- id: id || undefined,
- name,
- domains,
- path: pathVal,
- target_url: target,
- protocol: proto,
- certificate: cert,
- strip_path: stripPath,
- http_to_https: httpToHttps,
- preserve_host: preserveHost,
- insecure_tls: insecureTLS,
- enabled,
- comment
- };
- try {
- const url = id ? `${API_BASE}/proxy/rules/${encodeURIComponent(id)}` : `${API_BASE}/proxy/rules`;
- const method = id ? 'PUT' : 'POST';
- const res = await fetch(url, {
- method,
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(payload)
- });
- if (!res.ok) {
- const errData = await res.json().catch(() => ({}));
- throw new Error(errData.message || 'Failed to save proxy rule');
- }
- closeProxyRuleModal();
- showToast('Success', `Proxy rule "${name}" saved successfully`, 'success');
- await loadReverseProxy(false);
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deleteProxyRule(id) {
- const rule = (state.proxyRules || []).find(r => r.id === id);
- const name = rule ? rule.name : id;
- if (!confirm(`Are you sure you want to delete proxy rule "${name}"?`)) {
- return;
- }
- try {
- const res = await fetch(`${API_BASE}/proxy/rules/${encodeURIComponent(id)}`, {
- method: 'DELETE'
- });
- if (!res.ok) {
- const errData = await res.json().catch(() => ({}));
- throw new Error(errData.message || 'Failed to delete rule');
- }
- showToast('Rule Deleted', `Proxy rule "${name}" removed`, 'success');
- await loadReverseProxy(false);
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function toggleProxyRuleState(id, currentState) {
- try {
- const res = await fetch(`${API_BASE}/proxy/rules/${encodeURIComponent(id)}/state`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ enabled: !currentState })
- });
- if (!res.ok) {
- const errData = await res.json().catch(() => ({}));
- throw new Error(errData.message || 'Failed to toggle rule state');
- }
- await loadReverseProxy(false);
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- function openProxyConfigModal() {
- const modal = document.getElementById('modal-proxy-config');
- if (!modal) return;
- const cfg = state.proxyConfig || { enabled: true, http_port: 80, https_port: 443, default_cert: '' };
- document.getElementById('proxy-cfg-enabled').checked = cfg.enabled !== false;
- document.getElementById('proxy-cfg-http-port').value = cfg.http_port || 80;
- document.getElementById('proxy-cfg-https-port').value = cfg.https_port || 443;
- populateDefaultProxyCertDropdown(cfg.default_cert || '');
- modal.classList.remove('hidden');
- }
- function closeProxyConfigModal() {
- const modal = document.getElementById('modal-proxy-config');
- if (modal) modal.classList.add('hidden');
- }
- async function saveProxyConfig(event) {
- event.preventDefault();
- const enabled = document.getElementById('proxy-cfg-enabled').checked;
- const httpPort = parseInt(document.getElementById('proxy-cfg-http-port').value, 10) || 80;
- const httpsPort = parseInt(document.getElementById('proxy-cfg-https-port').value, 10) || 443;
- const defaultCert = document.getElementById('proxy-cfg-default-cert').value;
- const payload = {
- enabled,
- http_port: httpPort,
- https_port: httpsPort,
- default_cert: defaultCert
- };
- try {
- const res = await fetch(`${API_BASE}/proxy/config`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(payload)
- });
- if (!res.ok) {
- const errData = await res.json().catch(() => ({}));
- throw new Error(errData.message || 'Failed to update proxy settings');
- }
- closeProxyConfigModal();
- showToast('Success', 'Reverse proxy settings updated', 'success');
- await loadReverseProxy(false);
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // ==================== SD-WAN Controller ====================
- async function loadSDWAN(manual = false) {
- try {
- const [groupsRes, telemetryRes] = await Promise.all([
- fetch(`${API_BASE}/sdwan/groups`),
- fetch(`${API_BASE}/sdwan/telemetry`)
- ]);
- if (!groupsRes.ok) throw new Error('Failed to load SD-WAN groups');
- state.sdwanGroups = await groupsRes.json() || [];
- if (telemetryRes.ok) {
- state.sdwanTelemetry = await telemetryRes.json() || {};
- }
- renderSDWANGroups(state.sdwanGroups);
- renderSDWANMembers(state.sdwanGroups);
- updateSDWANMetrics(state.sdwanTelemetry);
- if (manual) showToast('SD-WAN', 'SD-WAN groups and live telemetry reloaded', 'success');
- } catch (err) {
- console.error('loadSDWAN error:', err);
- if (manual) showToast('Error', err.message, 'error');
- }
- }
- function updateSDWANMetrics(telemetry) {
- const groups = state.sdwanGroups || [];
- const t = telemetry || {};
- const badge = document.getElementById('badge-sdwan-count');
- if (badge) badge.textContent = groups.length;
- const metricGroups = document.getElementById('sdwan-metric-groups');
- if (metricGroups) metricGroups.textContent = `${t.active_groups || 0} / ${t.total_groups || groups.length}`;
- const metricHealthy = document.getElementById('sdwan-metric-healthy');
- if (metricHealthy) metricHealthy.textContent = t.healthy_members || 0;
- const metricDegraded = document.getElementById('sdwan-metric-degraded');
- if (metricDegraded) metricDegraded.textContent = t.degraded_members || 0;
- const metricDown = document.getElementById('sdwan-metric-down');
- if (metricDown) metricDown.textContent = t.down_members || 0;
- }
- function renderSDWANGroups(groups) {
- const tbody = document.getElementById('sdwan-groups-table-body');
- if (!tbody) return;
- if (!groups || groups.length === 0) {
- tbody.innerHTML = '<tr><td colspan="8" class="py-8 text-center text-slate-500 text-xs font-sans">No SD-WAN groups configured yet. Click "Create SD-WAN Group" to begin.</td></tr>';
- return;
- }
- tbody.innerHTML = groups.map(g => {
- const isEnabled = g.disabled !== true;
- const members = g.members || [];
- const totalWeight = members.filter(m => !m.disabled).reduce((sum, m) => sum + (m.weight || 50), 0) || 1;
- // Build distribution progress bar
- let distHtml = '';
- if (members.length === 0) {
- distHtml = '<span class="text-slate-500 text-[11px] font-sans">No links attached</span>';
- } else if (g.mode === 'weighted' || g.mode === 'pcc') {
- const colors = ['bg-amber-500', 'bg-cyan-500', 'bg-emerald-500', 'bg-purple-500', 'bg-rose-500'];
- const segments = members.map((m, idx) => {
- const pct = m.disabled ? 0 : Math.round(((m.weight || 50) / totalWeight) * 100);
- const col = colors[idx % colors.length];
- return `<div class="${col} h-2 transition-all relative group" style="width: ${pct}%" title="${escapeHtml(m.interface)}: ${pct}%"></div>`;
- }).join('');
- const labels = members.map((m, idx) => {
- const pct = m.disabled ? '0%' : `${Math.round(((m.weight || 50) / totalWeight) * 100)}%`;
- const textCol = ['text-amber-400', 'text-cyan-400', 'text-emerald-400', 'text-purple-400', 'text-rose-400'][idx % 5];
- return `<span class="${textCol} text-[10px] font-mono mr-2">${escapeHtml(m.interface)}: ${pct}</span>`;
- }).join('');
- distHtml = `
- <div class="w-48 bg-slate-800 rounded-full h-2 overflow-hidden flex mb-1 border border-slate-700/50">${segments}</div>
- <div class="flex flex-wrap">${labels}</div>
- `;
- } else if (g.mode === 'lowest-latency') {
- distHtml = '<span class="text-emerald-400 text-[11px] font-sans">⚡ Auto: lowest RTT probe</span>';
- } else if (g.mode === 'lowest-loss') {
- distHtml = '<span class="text-cyan-400 text-[11px] font-sans">🛡 Auto: minimum packet loss</span>';
- } else if (g.mode === 'failover') {
- distHtml = '<span class="text-amber-400 text-[11px] font-sans">🔄 Priority Failover (Active-Backup)</span>';
- }
- let modeBadge = '';
- switch (g.mode) {
- case 'weighted':
- modeBadge = '<span class="px-2 py-0.5 rounded bg-amber-500/20 text-amber-300 border border-amber-500/30 text-[10px] font-bold">Weighted LB</span>';
- break;
- case 'pcc':
- modeBadge = '<span class="px-2 py-0.5 rounded bg-purple-500/20 text-purple-300 border border-purple-500/30 text-[10px] font-bold">PCC Hashing</span>';
- break;
- case 'lowest-latency':
- modeBadge = '<span class="px-2 py-0.5 rounded bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 text-[10px] font-bold">Lowest Latency SLA</span>';
- break;
- case 'lowest-loss':
- modeBadge = '<span class="px-2 py-0.5 rounded bg-cyan-500/20 text-cyan-300 border border-cyan-500/30 text-[10px] font-bold">Lowest Loss SLA</span>';
- break;
- case 'failover':
- modeBadge = '<span class="px-2 py-0.5 rounded bg-rose-500/20 text-rose-300 border border-rose-500/30 text-[10px] font-bold">Failover</span>';
- break;
- default:
- modeBadge = `<span class="px-2 py-0.5 rounded bg-slate-800 text-slate-300 text-[10px] font-bold">${escapeHtml(g.mode)}</span>`;
- }
- const autoNatBadge = g.auto_nat
- ? '<span class="text-emerald-400 text-[11px]">Enabled</span>'
- : '<span class="text-slate-500 text-[11px]">Disabled</span>';
- return `
- <tr class="hover:bg-slate-800/40 transition">
- <td class="py-3 px-4">
- <button onclick="toggleSDWANGroupState('${escapeHtml(g.id)}', ${isEnabled})" class="relative inline-flex h-5 w-9 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none ${isEnabled ? 'bg-amber-500' : 'bg-slate-700'}" title="${isEnabled ? 'Click to disable' : 'Click to enable'}">
- <span class="inline-block h-4 w-4 transform rounded-full bg-white shadow transition duration-200 ease-in-out ${isEnabled ? 'translate-x-4' : 'translate-x-0'}"></span>
- </button>
- </td>
- <td class="py-3 px-4">
- <div class="font-bold text-white text-xs flex items-center gap-1.5">
- <span class="px-2 py-0.5 rounded bg-amber-950/60 text-amber-300 border border-amber-800/40 font-mono text-[11px] font-bold">${escapeHtml(g.name)}</span>
- ${g.comment ? `<span class="text-slate-400 text-[10px] font-sans truncate max-w-[150px]" title="${escapeHtml(g.comment)}">(${escapeHtml(g.comment)})</span>` : ''}
- </div>
- </td>
- <td class="py-3 px-4">${modeBadge}</td>
- <td class="py-3 px-4">${distHtml}</td>
- <td class="py-3 px-4">
- <span class="px-2 py-0.5 rounded bg-slate-800 text-slate-200 border border-slate-700 font-mono text-[11px]">${members.length} links</span>
- </td>
- <td class="py-3 px-4 text-slate-300 font-mono text-xs">${g.probe_interval || 3}s</td>
- <td class="py-3 px-4">${autoNatBadge}</td>
- <td class="py-3 px-4 text-right">
- <div class="flex items-center justify-end gap-1.5">
- <button onclick="openAddSDWANMemberModal('${escapeHtml(g.id)}')" class="p-1.5 rounded-lg bg-slate-800 hover:bg-slate-700 text-amber-300 transition" title="Add Member Link">
- <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/></svg>
- </button>
- <button onclick="openEditSDWANGroupModal('${escapeHtml(g.id)}')" class="p-1.5 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-300 transition" title="Edit Group">
- <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/></svg>
- </button>
- <button onclick="deleteSDWANGroup('${escapeHtml(g.id)}')" class="p-1.5 rounded-lg bg-rose-950/40 hover:bg-rose-900/60 text-rose-400 border border-rose-800/40 transition" title="Delete Group">
- <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
- </button>
- </div>
- </td>
- </tr>
- `;
- }).join('');
- }
- function renderSDWANMembers(groups) {
- const tbody = document.getElementById('sdwan-members-table-body');
- if (!tbody) return;
- const allMembers = [];
- (groups || []).forEach(g => {
- (g.members || []).forEach(m => {
- allMembers.push({ ...m, group_id: g.id, group_name: g.name });
- });
- });
- if (allMembers.length === 0) {
- tbody.innerHTML = '<tr><td colspan="11" class="py-8 text-center text-slate-500 text-xs font-sans">No member WAN links configured. Click "Add Member Link" above.</td></tr>';
- return;
- }
- tbody.innerHTML = allMembers.map(m => {
- const isEnabled = m.disabled !== true;
- let statusBadge = '<span class="px-2 py-0.5 rounded bg-emerald-500/20 text-emerald-400 border border-emerald-500/30 text-[10px] font-bold">HEALTHY</span>';
- if (!isEnabled) {
- statusBadge = '<span class="px-2 py-0.5 rounded bg-slate-800 text-slate-400 border border-slate-700 text-[10px]">DISABLED</span>';
- } else if (m.status === 'DEGRADED') {
- statusBadge = '<span class="px-2 py-0.5 rounded bg-amber-500/20 text-amber-400 border border-amber-500/30 text-[10px] font-bold">DEGRADED</span>';
- } else if (m.status === 'DOWN') {
- statusBadge = '<span class="px-2 py-0.5 rounded bg-rose-500/20 text-rose-400 border border-rose-500/30 text-[10px] font-bold animate-pulse">DOWN</span>';
- }
- const latColor = m.live_latency > (m.max_latency || 250) ? 'text-amber-400' : 'text-emerald-400';
- const lossColor = m.packet_loss > (m.max_loss || 20) ? 'text-rose-400' : 'text-slate-300';
- return `
- <tr class="hover:bg-slate-800/40 transition">
- <td class="py-3 px-4">
- <button onclick="toggleSDWANMemberState('${escapeHtml(m.group_id)}', '${escapeHtml(m.id)}', ${isEnabled})" class="relative inline-flex h-5 w-9 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none ${isEnabled ? 'bg-amber-500' : 'bg-slate-700'}" title="${isEnabled ? 'Click to disable link' : 'Click to enable link'}">
- <span class="inline-block h-4 w-4 transform rounded-full bg-white shadow transition duration-200 ease-in-out ${isEnabled ? 'translate-x-4' : 'translate-x-0'}"></span>
- </button>
- </td>
- <td class="py-3 px-4">
- <span class="px-2 py-0.5 rounded bg-amber-950/60 text-amber-300 border border-amber-800/40 font-mono text-[11px] font-bold">${escapeHtml(m.group_name)}</span>
- </td>
- <td class="py-3 px-4">
- <div class="font-bold text-white text-xs font-mono">${escapeHtml(m.interface)}</div>
- ${m.comment ? `<div class="text-[10px] text-slate-500 font-sans">${escapeHtml(m.comment)}</div>` : ''}
- </td>
- <td class="py-3 px-4 text-slate-300 font-mono text-xs">${escapeHtml(m.gateway || '(auto)')}</td>
- <td class="py-3 px-4">
- <div class="text-xs font-mono text-white">W: ${m.weight || 50}</div>
- <div class="text-[10px] text-slate-500">Prio: ${m.priority || 1}</div>
- </td>
- <td class="py-3 px-4">${statusBadge}</td>
- <td class="py-3 px-4 text-cyan-400 font-mono text-xs">${escapeHtml(m.target_probe || '1.1.1.1')}</td>
- <td class="py-3 px-4 font-mono text-xs ${latColor}">
- ${m.live_latency ? `${m.live_latency.toFixed(1)} ms` : '<span class="text-slate-500">--</span>'}
- </td>
- <td class="py-3 px-4 font-mono text-xs ${lossColor}">
- ${m.packet_loss !== undefined ? `${m.packet_loss.toFixed(1)}%` : '<span class="text-slate-500">--</span>'}
- </td>
- <td class="py-3 px-4 font-mono text-xs text-slate-400">
- ${m.jitter ? `${m.jitter.toFixed(1)} ms` : '<span class="text-slate-500">--</span>'}
- </td>
- <td class="py-3 px-4 text-right">
- <div class="flex items-center justify-end gap-1.5">
- <button onclick="openEditSDWANMemberModal('${escapeHtml(m.group_id)}', '${escapeHtml(m.id)}')" class="p-1.5 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-300 transition" title="Edit Member">
- <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/></svg>
- </button>
- <button onclick="deleteSDWANMember('${escapeHtml(m.group_id)}', '${escapeHtml(m.interface)}')" class="p-1.5 rounded-lg bg-rose-950/40 hover:bg-rose-900/60 text-rose-400 border border-rose-800/40 transition" title="Remove Link">
- <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
- </button>
- </div>
- </td>
- </tr>
- `;
- }).join('');
- }
- // Modal handling for SD-WAN Groups
- function openAddSDWANGroupModal() {
- const modal = document.getElementById('modal-sdwan-group');
- if (!modal) return;
- document.getElementById('sdwan-group-modal-title').querySelector('span').textContent = 'Create SD-WAN Group';
- document.getElementById('sdwan-group-id').value = '';
- document.getElementById('sdwan-group-name').value = `sdwan${(state.sdwanGroups || []).length}`;
- document.getElementById('sdwan-group-name').disabled = false;
- document.getElementById('sdwan-group-mode').value = 'weighted';
- document.getElementById('sdwan-group-pcc-container').classList.add('hidden');
- document.getElementById('sdwan-group-hash-fields').value = 'both-addresses-and-ports';
- document.getElementById('sdwan-group-probe-interval').value = 3;
- document.getElementById('sdwan-group-auto-nat').checked = true;
- document.getElementById('sdwan-group-comment').value = '';
- modal.classList.remove('hidden');
- }
- function openEditSDWANGroupModal(id) {
- const group = (state.sdwanGroups || []).find(g => g.id === id);
- if (!group) return;
- const modal = document.getElementById('modal-sdwan-group');
- if (!modal) return;
- document.getElementById('sdwan-group-modal-title').querySelector('span').textContent = `Edit SD-WAN Group (${group.name})`;
- document.getElementById('sdwan-group-id').value = group.id;
- document.getElementById('sdwan-group-name').value = group.name;
- document.getElementById('sdwan-group-name').disabled = true;
- document.getElementById('sdwan-group-mode').value = group.mode || 'weighted';
- if (group.mode === 'pcc') {
- document.getElementById('sdwan-group-pcc-container').classList.remove('hidden');
- } else {
- document.getElementById('sdwan-group-pcc-container').classList.add('hidden');
- }
- document.getElementById('sdwan-group-hash-fields').value = group.hash_fields || 'both-addresses-and-ports';
- document.getElementById('sdwan-group-probe-interval').value = group.probe_interval || 3;
- document.getElementById('sdwan-group-auto-nat').checked = group.auto_nat !== false;
- document.getElementById('sdwan-group-comment').value = group.comment || '';
- modal.classList.remove('hidden');
- }
- function closeSDWANGroupModal() {
- const modal = document.getElementById('modal-sdwan-group');
- if (modal) modal.classList.add('hidden');
- }
- function onSDWANModeChange() {
- const mode = document.getElementById('sdwan-group-mode').value;
- const pccContainer = document.getElementById('sdwan-group-pcc-container');
- if (pccContainer) {
- if (mode === 'pcc') pccContainer.classList.remove('hidden');
- else pccContainer.classList.add('hidden');
- }
- }
- async function saveSDWANGroup(event) {
- event.preventDefault();
- const id = document.getElementById('sdwan-group-id').value;
- const name = document.getElementById('sdwan-group-name').value.trim();
- const mode = document.getElementById('sdwan-group-mode').value;
- const hashFields = document.getElementById('sdwan-group-hash-fields').value;
- const probeInterval = parseInt(document.getElementById('sdwan-group-probe-interval').value, 10) || 3;
- const autoNAT = document.getElementById('sdwan-group-auto-nat').checked;
- const comment = document.getElementById('sdwan-group-comment').value.trim();
- const existing = (state.sdwanGroups || []).find(g => g.id === id);
- const payload = {
- id: id || undefined,
- name,
- mode,
- hash_fields: mode === 'pcc' ? hashFields : undefined,
- probe_interval: probeInterval,
- auto_nat: autoNAT,
- comment,
- members: existing ? existing.members : undefined
- };
- try {
- const res = await fetch(`${API_BASE}/sdwan/groups`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(payload)
- });
- if (!res.ok) {
- const err = await res.json().catch(() => ({}));
- throw new Error(err.message || 'Failed to save SD-WAN group');
- }
- closeSDWANGroupModal();
- showToast('Success', `SD-WAN group ${name} saved successfully`, 'success');
- await loadSDWAN(false);
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function toggleSDWANGroupState(id, currentState) {
- try {
- const res = await fetch(`${API_BASE}/sdwan/groups/${id}/state`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ disabled: currentState })
- });
- if (!res.ok) throw new Error('Failed to update group state');
- await loadSDWAN(false);
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deleteSDWANGroup(id) {
- const group = (state.sdwanGroups || []).find(g => g.id === id);
- const name = group ? group.name : id;
- if (!confirm(`Are you sure you want to delete SD-WAN group "${name}"? Member routing tables will be cleared.`)) return;
- try {
- const res = await fetch(`${API_BASE}/sdwan/groups/${id}`, {
- method: 'DELETE'
- });
- if (!res.ok) {
- const err = await res.json().catch(() => ({}));
- throw new Error(err.message || 'Failed to delete SD-WAN group');
- }
- showToast('Deleted', `SD-WAN group ${name} removed`, 'success');
- await loadSDWAN(false);
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // Modal handling for SD-WAN Members
- function populateSDWANGroupsSelect(selectedId = '') {
- const sel = document.getElementById('sdwan-member-group-id');
- if (!sel) return;
- sel.innerHTML = '';
- (state.sdwanGroups || []).forEach(g => {
- const opt = document.createElement('option');
- opt.value = g.id;
- opt.textContent = `${g.name} (${g.mode})`;
- if (g.id === selectedId) opt.selected = true;
- sel.appendChild(opt);
- });
- }
- function populateSDWANMemberInterfaceSelect(selectedVal = '') {
- const sel = document.getElementById('sdwan-member-interface');
- if (!sel) return;
- sel.innerHTML = '';
- (state.interfaces || []).forEach(i => {
- const opt = document.createElement('option');
- opt.value = i.name;
- opt.textContent = `${i.name} (${i.role || i.type})`;
- if (i.name === selectedVal) opt.selected = true;
- sel.appendChild(opt);
- });
- }
- function openAddSDWANMemberModal(defaultGroupId = null) {
- const modal = document.getElementById('modal-sdwan-member');
- if (!modal) return;
- if (!state.sdwanGroups || state.sdwanGroups.length === 0) {
- showToast('Notice', 'Please create an SD-WAN group first before adding member links', 'warning');
- return;
- }
- document.getElementById('sdwan-member-modal-title').querySelector('span').textContent = 'Add Member Link';
- document.getElementById('sdwan-member-id').value = '';
- populateSDWANGroupsSelect(defaultGroupId || (state.sdwanGroups[0] && state.sdwanGroups[0].id));
- populateSDWANMemberInterfaceSelect();
- document.getElementById('sdwan-member-gateway').value = '';
- document.getElementById('sdwan-member-weight').value = 50;
- document.getElementById('sdwan-member-priority').value = 1;
- document.getElementById('sdwan-member-probe').value = '1.1.1.1';
- document.getElementById('sdwan-member-max-lat').value = 250;
- document.getElementById('sdwan-member-max-loss').value = 20;
- document.getElementById('sdwan-member-comment').value = '';
- modal.classList.remove('hidden');
- }
- function openEditSDWANMemberModal(groupId, memberId) {
- const group = (state.sdwanGroups || []).find(g => g.id === groupId);
- if (!group) return;
- const member = (group.members || []).find(m => m.id === memberId);
- if (!member) return;
- const modal = document.getElementById('modal-sdwan-member');
- if (!modal) return;
- document.getElementById('sdwan-member-modal-title').querySelector('span').textContent = `Edit Member Link (${member.interface})`;
- document.getElementById('sdwan-member-id').value = member.id;
- populateSDWANGroupsSelect(group.id);
- document.getElementById('sdwan-member-group-id').disabled = true;
- populateSDWANMemberInterfaceSelect(member.interface);
- document.getElementById('sdwan-member-interface').disabled = true;
- document.getElementById('sdwan-member-gateway').value = member.gateway || '';
- document.getElementById('sdwan-member-weight').value = member.weight || 50;
- document.getElementById('sdwan-member-priority').value = member.priority || 1;
- document.getElementById('sdwan-member-probe').value = member.target_probe || '1.1.1.1';
- document.getElementById('sdwan-member-max-lat').value = member.max_latency || 250;
- document.getElementById('sdwan-member-max-loss').value = member.max_loss || 20;
- document.getElementById('sdwan-member-comment').value = member.comment || '';
- modal.classList.remove('hidden');
- }
- function closeSDWANMemberModal() {
- const modal = document.getElementById('modal-sdwan-member');
- if (modal) {
- document.getElementById('sdwan-member-group-id').disabled = false;
- document.getElementById('sdwan-member-interface').disabled = false;
- modal.classList.add('hidden');
- }
- }
- async function saveSDWANMember(event) {
- event.preventDefault();
- const id = document.getElementById('sdwan-member-id').value;
- const groupId = document.getElementById('sdwan-member-group-id').value;
- const iface = document.getElementById('sdwan-member-interface').value;
- const gateway = document.getElementById('sdwan-member-gateway').value.trim();
- const weight = parseInt(document.getElementById('sdwan-member-weight').value, 10) || 50;
- const priority = parseInt(document.getElementById('sdwan-member-priority').value, 10) || 1;
- const targetProbe = document.getElementById('sdwan-member-probe').value.trim() || '1.1.1.1';
- const maxLatency = parseInt(document.getElementById('sdwan-member-max-lat').value, 10) || 250;
- const maxLoss = parseInt(document.getElementById('sdwan-member-max-loss').value, 10) || 20;
- const comment = document.getElementById('sdwan-member-comment').value.trim();
- const payload = {
- id: id || undefined,
- interface: iface,
- gateway,
- weight,
- priority,
- target_probe: targetProbe,
- max_latency: maxLatency,
- max_loss: maxLoss,
- comment
- };
- try {
- const res = await fetch(`${API_BASE}/sdwan/groups/${groupId}/members`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(payload)
- });
- if (!res.ok) {
- const err = await res.json().catch(() => ({}));
- throw new Error(err.message || 'Failed to save member link');
- }
- closeSDWANMemberModal();
- showToast('Success', `Link ${iface} saved to SD-WAN group`, 'success');
- await loadSDWAN(false);
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function toggleSDWANMemberState(groupId, memberId, currentState) {
- const group = (state.sdwanGroups || []).find(g => g.id === groupId);
- if (!group) return;
- const member = (group.members || []).find(m => m.id === memberId);
- if (!member) return;
- const payload = {
- ...member,
- disabled: currentState
- };
- try {
- const res = await fetch(`${API_BASE}/sdwan/groups/${groupId}/members`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(payload)
- });
- if (!res.ok) throw new Error('Failed to update member state');
- await loadSDWAN(false);
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deleteSDWANMember(groupId, iface) {
- if (!confirm(`Are you sure you want to remove link "${iface}" from this SD-WAN group?`)) return;
- try {
- const res = await fetch(`${API_BASE}/sdwan/groups/${groupId}/members/${iface}`, {
- method: 'DELETE'
- });
- if (!res.ok) {
- const err = await res.json().catch(() => ({}));
- throw new Error(err.message || 'Failed to remove member link');
- }
- showToast('Removed', `Link ${iface} removed from SD-WAN group`, 'success');
- await loadSDWAN(false);
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
|